convert factors to numeric in dataframe

2019-07-29 11:25发布

I have a very large data frame containing 2 levels of a factor, levels "No" and "Yes". I would like to replace the levels to numeric values, so that "No" turns into 0, and "Yes" turns into 1.

I would like to apply a function that works on the data frame.

A simple example to work on:

> df
  a   b   c   d
1 1  No Yes   1
2 2  No  No   3
3 3 Yes  No 123
4 4 Yes Yes  12
5 5  No Yes 231
6 6  No  No  21
7 7 Yes  No  21
8 8 Yes  No  21

> str(df)
'data.frame':   8 obs. of  4 variables:
 $ a: int  1 2 3 4 5 6 7 8
 $ b: Factor w/ 2 levels "No","Yes": 1 1 2 2 1 1 2 2
 $ c: Factor w/ 2 levels "No","Yes": 2 1 1 2 2 1 1 1
 $ d: int  1 3 123 12 231 21 21 21

Wanted results :

> df
  a b c   d
1 1 0 1   1
2 2 0 0   3
3 3 1 0 123
4 4 1 1  12
5 5 0 1 231
6 6 0 0  21
7 7 1 0  21

> str(df)
'data.frame':   8 obs. of  4 variables:
 $ a: int  1 2 3 4 5 6 7 8
 $ b: int  0 0 1 1 0 0 1 1
 $ c: int  1 0 0 1 1 0 0 0
 $ d: int  1 3 123 12 231 21 21 21

1条回答
乱世女痞
2楼-- · 2019-07-29 12:02

Try

df[2:3] <- lapply(df[2:3], function(x) as.numeric(x)-1)
df
#   a b c   d
#1 1 0 1   1
#2 2 0 0   3
#3 3 1 0 123
#4 4 1 1  12
#5 5 0 1 231
#6 6 0 0  21
#7 7 1 0  21
#8 8 1 0  21

This could be wrapped into a function

f1 <- function(dat){
 indx <- sapply(dat, is.factor)
 dat[indx] <- lapply(dat[indx], function(x) if(any(x %in% c("Yes",
             "No"))) as.numeric(x)-1 else x)
 dat 
}

f1(df)
查看更多
登录 后发表回答