将数据框列更改为数字因子

时间:2021-12-24 07:36:39

I am trying to change the first 20 columns in my data frame to Factor I can do it individually using

我正在尝试将数据框中的前20列更改为因子I可以单独使用

    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

干杯米克

1 个解决方案

#1


1  

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

#1


1  

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