[英]Changing Data frame columns to factor from numeric
I am trying to change the first 20 columns in my data frame to Factor I can do it individually using 我正在尝试将数据框中的前20列更改为因子,我可以使用
data[,1] <- as.factor(data[,1])
I have tried other methods to get the first 20 to change in one line of script but to no avail, the data frame has 90 columns of which I would like the rest to stay numeric 我尝试了其他方法来使前20个脚本在一行脚本中更改,但无济于事,数据框有90列,我希望其余的保持数值
I have looked around this site and can only find examples of changing all columns 我环顾了这个站点,只能找到更改所有列的示例
Cheers Mick 干杯米克
Use lapply
on the columns of interest: 在感兴趣的列上使用
lapply
:
Example: 例:
Sample data: 样本数据:
set.seed(1)
mydf <- data.frame(matrix(sample(1:5, 24, TRUE), ncol = 8))
str(mydf)
# 'data.frame': 3 obs. of 8 variables:
# $ X1: int 2 2 3
# $ X2: int 5 2 5
# $ X3: int 5 4 4
# $ X4: int 1 2 1
# $ X5: int 4 2 4
# $ X6: int 3 4 5
# $ X7: int 2 4 5
# $ X8: int 2 4 1
Converting specified columns: 转换指定的列:
## Change cols 4:8 to factors
mydf[4:8] <- lapply(mydf[4:8], as.factor)
str(mydf)
# 'data.frame': 3 obs. of 8 variables:
# $ X1: int 2 2 3
# $ X2: int 5 2 5
# $ X3: int 5 4 4
# $ X4: Factor w/ 2 levels "1","2": 1 2 1
# $ X5: Factor w/ 2 levels "2","4": 2 1 2
# $ X6: Factor w/ 3 levels "3","4","5": 1 2 3
# $ X7: Factor w/ 3 levels "2","4","5": 1 2 3
# $ X8: Factor w/ 3 levels "1","2","4": 2 3 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.