How to see all the character variable names at once of a data frame in r

AKRAM HUSSAIN KHAN
2 min readNov 9, 2022

--

Suppose we have a data frame named train and it has 30 columns. We can see all the column names by using the following:

names(train)

But we want the character variable names, not all the variable names.

If we use sapply(), we can see all the column names and their corresponding class.

sapply(train, class)

From here, we have to identify which is the character type and list it. But this is tedious and time-consuming. What if we have 400 columns rather than 30? It will be very difficult to identify all the character variables.

By the following line of code, we can see the class type and corresponding frequency of that class.

table(sapply(train, class))
character Date numeric
18 1 11

We see that there are 18 character variables whose names we have to find.

We can do it easily by using the following line of code:

names(which(sapply(train, is.character)))

Now, we can only see our required 18, character variable names.

We can use this for other types of variables also. Such as numeric, factor, etc.

names(which(sapply(train, is.numeric)))

Here are our required 11 numeric variable names.

--

--

No responses yet