简体   繁体   中英

Convert lines from factor to numeric?

this example:

dat=structure(list(X = structure(c(1L, 2L,3L), .Label = c("A", "B", "C"), class = "factor"), X10 = structure(c(1L,2L,3L), .Label = c("3","0", "2"), class = "factor"), X11 = structure(c(1L, 2L,3L), .Label = c("0", "2", "0"), class = "factor")), class = "data.frame", row.names = c(NA, -3L)) 

 dat=dat[,-1]

 fi=as.numeric(as.character(dat[1,] ))

 > fi
[1] 1 1

Which is not correct. I wonder what is wrong ?

as.numeric is for vector, you need to use apply if you want to apply this to a data frame:

apply(dat, MARGIN=2,FUN=as.numeric)

result:

      X10 X11
[1,]   3   0
[2,]   0   2
[3,]   2   0

For multiple columns of different class, we can have a check whether it is factor or not to do the conversion

library(dplyr)
dat %>%
    mutate_if(is.factor, funs(as.numeric(as.character(.))))

and if all the columns are factor , then use mutate_all

dat %>%
   mutate_all(funs(as.numeric(as.character(.))))

The base R way if all columns are factor , use lapply and assign it to the original object

dat[] <- lapply(dat, function(x) as.numeric(as.character(x)))

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