在数据框中将因子转换为数字 [英] convert factors to numeric in dataframe

查看:24
本文介绍了在数据框中将因子转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的数据框,其中包含 2 个因子级别,级别否"和是".我想将级别替换为数值,以便否"变为 0,是"变为 1.

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.

一个简单的例子:

> 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

想要的结果:

> 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

推荐答案

尝试

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

这可以包装成一个函数

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)

这篇关于在数据框中将因子转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆