Reputation: 585
I have data frame in R with four columns and I am trying to get class of each variable using for loop, depending on a class of variable I could write a further code. Below is the data frame.
var1 var2 var3 var4
1 1 a a s
2 2 g a s
3 3 b s
4 4 n s s
5 NA m f f
6 6 r g v
7 7 t b
8 8 j
9 9 y i g
10 10 h i t
As of now I have tried below code but it is giving NULL for a class of variable
for (i in names(df)){
print(names(df[i]))
name <- names(df[i])
print(class(df$name))
}
Result with above code:
[1] "var1"
[1] "NULL"
[1] "var2"
[1] "NULL"
[1] "var3"
[1] "NULL"
[1] "var4"
[1] "NULL"
Expecting Result
[1] "var1"
[1] "integer"
[1] "var2"
[1] "factor"
[1] "var3"
[1] "factor"
[1] "var4"
[1] "integer"
Requesting your help.
Upvotes: 1
Views: 2348
Reputation: 308
Since data.frame
s are really just a list
of columns, I do this often using lapply
:
lapply(df, class)
As for the for
loop you have in the example, when you call df$name
, R is trying to find the column called "name". Instead, you want df[, name]
:
for (i in names(df)){
name <- names(df[i])
print(name)
print(class(df[, name]))
}
Upvotes: 4
Reputation: 4102
Using mtcars as an example:
for (i in names(mtcars)){
print(names(mtcars[i]))
name <- names(mtcars[i])
print(class(mtcars[,i]))
}
Upvotes: 1