gpt4 book ai didi

r - 如何从组合的多个列中创建一个列?

转载 作者:行者123 更新时间:2023-12-01 23:06:58 24 4
gpt4 key购买 nike

我正在使用的数据集记录了受访者的种族。响应记录在多个变量中,并且允许受访者选择一个以上。示例:

ethnicity1     ethnicity2     ethnicity3    ethnicity4     ethnicity5     ethnicity6
1 0 0 0 0 0
0 2 0 0 0 0
0 0 3 4 0 0

每个种族都有自己的专栏。我已经使用 recode 命令对每一列进行了重新编码,以便不同的数字代表不同的种族(即,黑色代表 1,白色代表 2,等等)来尝试制作一个单一的种族变量

A) 从组合的多个列中创建一个列

B) 拥有它以便报告多个列的任何人都被指定为“多个”。

我预期的输出是这样的:

Ethnicity
1
2
999

(我不确定为了编码目的最好是用一个数值来表示多个种族,还是让它是一个字符值,如“multiple”)

最初,我想这样做,但它并没有像我希望的那样进行。

Ethnicity <- df %>% dplyr::na_if(0)
## create column for ethnicity
Ethnicity %>% unite("RaceEthnicity", ethnicity1:ethnicity5, na.rm = TRUE, remove = FALSE)

最佳答案

这是一个 tidyverse 解决方案。我假设您的数据有一个针对受访者的列。我添加了它并将其命名为 ID

要了解发生了什么,您可以通过连续添加每一行来运行代码,直到但不包括管道 (%>%) 并查看输出。

用于 pivot_longer 的列将取决于您的真实数据:此处种族在 1-6 中,ID 在 7 中。

library(dplyr)
library(tidyr)

mydata %>%
# add IDs for respondent
mutate(ID = LETTERS[1:3]) %>%
# convert to 'long' format
pivot_longer(1:6) %>%
# remove zero value rows
filter(value != 0) %>%
# group by person
group_by(ID) %>%
# use value where there is one row per person, otherwise use 999
# we need doubles for both values (existing are int)
summarise(ethnicity = case_when(n() == 1 ~ as.double(value),
TRUE ~ 999)) %>%
ungroup() %>%
# discard duplicate rows
distinct()

结果:

ID    ethnicity
<chr> <dbl>
1 A 1
2 B 2
3 C 999

具有更正列名的示例数据:

mydata <- structure(list(ethnicity1 = c(1L, 0L, 0L), 
ethnicity2 = c(0L, 2L, 0L),
ethnicity3 = c(0L, 0L, 3L),
ethnicity4 = c(0L, 0L, 4L),
ethnicity5 = c(0L, 0L, 0L),
ethnicity6 = c(0L, 0L, 0L)),
class = "data.frame",
row.names = c(NA, -3L))

关于r - 如何从组合的多个列中创建一个列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70705703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com