将列转换为数据框列表中的因子 [英] converting columns to factor over list of dataframes
本文介绍了将列转换为数据框列表中的因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将数据帧列表中的几列转换为因子.我已经尝试过了,但是似乎没有将列转换为因子:
I'm trying to convert several columns in a list of dataframes into factors. I've tried this, but it doesn't seem to convert the columns into factors:
factor_cols_REx <- c('GESLACHT','GEVKL','BEROEP')
for (i in (1:9)) {
dataset_RE10_2014[[i]] <- lapply(dataset_RE10_2014[[i]][factor_cols_REx],factor)
dataset_RE10_2015[[i]] <- lapply(dataset_RE10_2015[[i]][factor_cols_REx],factor)
}
关于如何解决此问题的任何想法?
Any ideas on how to fix this?
推荐答案
让我知道我是否正确理解
Let me know if I understood correctly
#DATA
dat = list(A = mtcars, B = mtcars)
#Columns we want to convert to factor
factor_cols = c("mpg", "hp")
#Go through the list using lapply and change specific columns to factor in each sub-group
#Modified from https://stackoverflow.com/a/33180265/7128934
dat2 = lapply(dat, function(x){
x[factor_cols] = lapply(x[factor_cols], factor)
x
})
#Check class in output list
lapply(dat2, function(x) sapply(x, class))
#$A
# mpg cyl disp hp drat wt qsec vs am gear carb
# "factor" "numeric" "numeric" "factor" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric"
#$B
# mpg cyl disp hp drat wt qsec vs am gear carb
# "factor" "numeric" "numeric" "factor" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric"
#Check class in input list
lapply(dat, function(x) sapply(x, class))
#$A
# mpg cyl disp hp drat wt qsec vs am gear carb
#"numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric"
#$B
# mpg cyl disp hp drat wt qsec vs am gear carb
#"numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric"
这篇关于将列转换为数据框列表中的因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文