繁体   English   中英

如何根据多个现有列中的数据对新列使用 mutate

[英]How to use mutate for a new column based the data in multiple existing columns

早上好,

这是我的数据集,包含不同客户种族的数据。

White  Asian  Black  Native  Islander  Other
1       0       0      0       0         0
0       1       0      0       0         0
0       0       0      1       0         0
0       0       1      0       0         0
1       0       0      0       1         0
0       0       0      0       0         1

数据以布尔值存储,其中 0 = 否,1 = 是

因此,如果客户的列白色为 1,则它们是白色的。

但是,如果客户对白人和岛民的评分为 1,那么他们就是多种族。

所以这将是我想要的输出

White  Asian  Black  Native  Islander  Other   Race
1       0       0      0       0         0     White
0       1       0      0       0         0     Asian
0       0       0      1       0         0     Native
0       0       1      0       0         0     Black
1       0       0      0       1         0     Multi-Racial 
0       0       0      0       0         1     Other

我熟悉 mutate() 但我只使用了基于一列的 mutate。

任何人都可以提供可以帮助我获得所需输出的代码吗?

使用ifelse()max.col()应该可以得到你想要的。 对于只有一个值的行,您索引该值所在的名称,否则为"Multi-Racial"

df1$Race <- ifelse(rowSums(df1) == 1, names(df1)[max.col(df1)], "Multi-Racial")
df1
  White Asian Black Native Islander Other         Race
1     1     0     0      0        0     0        White
2     0     1     0      0        0     0        Asian
3     0     0     0      1        0     0       Native
4     0     0     1      0        0     0        Black
5     1     0     0      0        1     0 Multi-Racial
6     0     0     0      0        0     1        Other

或者,使用mutate()

df1 %>%
  mutate(Race = ifelse(rowSums(.) == 1, names(.)[max.col(.)], "Multi-Racial"))

数据

df1 <- read.table(header = T, text = "White  Asian  Black  Native  Islander  Other
1       0       0      0       0         0
0       1       0      0       0         0
0       0       0      1       0         0
0       0       1      0       0         0
1       0       0      0       1         0
0       0       0      0       0         1")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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