简体   繁体   中英

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

    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

I have looked around this site and can only find examples of changing all columns

Cheers Mick

Use lapply on the columns of interest:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM