Loop through dataframe column names - R
70,375
To answer the exact question and fix the code given, see the example below
df <- iris # data
for (i in colnames(df)){
print(class(df[[i]]))
}
# [1] "numeric"
# [1] "numeric"
# [1] "numeric"
# [1] "numeric"
# [1] "factor"
- you need to used
colnames
to get the column names ofdf
. - you access each column using
df[[i]]
if you want to know the class of that.df[i]
is of classdata.frame
.
Related videos on Youtube
Author by
Chris
Updated on June 19, 2020Comments
-
Chris almost 4 years
I'm trying to loop through the columns names of a dataframe, and evaluate which class is each column.
for (i in columns(df)){ class(df$i) }
I have tried everything, except the right way..
PS: I'm trying to do in this way because after I have to put different conditions for each class.
-
Sathish about 6 years
sapply(df, class)
-
Jorge about 6 years
for (i in 1:length(df)){ class(df[,i]) }
-
hpesoj626 about 6 yearsI don't know what operations you want to do later, but are you familiar with
dplyr::mutate_if
ordplyr::summarise_if
sets of functions?
-
-
viridius about 4 yearsIs it possible to begin looping on a different column (e.g., column 11) other than the first column?
-
Christopher Moore almost 4 yearsPlease provide some explanation to go with this code.