我想要获取参与者ID和他们所讲的语言的数据,然后创建一个新的列,对每个参与者所讲的所有语言进行汇总。列是ID,每种语言的0=“不说话”和1=“确实说话”,包括一个“其他”的列,然后是一个单独的列,指定另一种语言是什么,"Other.Lang“。我只想对具有二进制值的列进行子集,并为每个参与者创建这个新列的和。
首先是我的数据。
Participant.Private.ID French Spanish Dutch Czech Russian Hebrew Chinese German Italian Japanese Korean Portuguese Other Other.Lang
1 5133249 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2 5136082 0 0 0 0 0 0 0 0 0 0 0 0 0 0
3 5140442 0 1 0 0 0 0 0 0 0 0 0 0 0 0
4 5141991 0 1 0 0 0 0 0 0 1 0 0 0 0 0
5 5143476 0 0 0 0 0 0 0 0 0 0 0 0 0 0
6 5145250 0 0 0 0 0 0 0 0 0 0 0 0 1 Malay
7 5146081 0 0 0 0 0 0 0 0 0 0 0 0 0 0结构如下:
str(part_langs)
grouped_df [7 x 15] (S3: grouped_df/tbl_df/tbl/data.frame)
$ Participant.Private.ID: num [1:7] 5133249 5136082 5140442 5141991 5143476 ...
$ French : num [1:7] 0 0 0 0 0 0 0
$ Spanish : num [1:7] 0 0 1 1 0 0 0
$ Dutch : num [1:7] 0 0 0 0 0 0 0
$ Czech : num [1:7] 0 0 0 0 0 0 0
$ Russian : num [1:7] 0 0 0 0 0 0 0
$ Hebrew : num [1:7] 0 0 0 0 0 0 0
$ Chinese : num [1:7] 0 0 0 0 0 0 0
$ German : num [1:7] 0 0 0 0 0 0 0
$ Italian : num [1:7] 0 0 0 1 0 0 0
$ Japanese : num [1:7] 0 0 0 0 0 0 0
$ Korean : num [1:7] 0 0 0 0 0 0 0
$ Portuguese : num [1:7] 0 0 0 0 0 0 0
$ Other : num [1:7] 0 0 0 0 0 1 0
$ Other.Lang : chr [1:7] "0" "0" "0" "0" ...
- attr(*, "groups")= tibble [7 x 2] (S3: tbl_df/tbl/data.frame)
..$ Participant.Private.ID: num [1:7] 5133249 5136082 5140442 5141991 5143476 ...我认为这应该有效:
num <- part_langs %>%
mutate(num.langs = rowSums(part_langs[2:14]))
num但是,我一直收到以下错误消息:
Error: Problem with `mutate()` input `num.langs`.
x Input `num.langs` can't be recycled to size 1.
i Input `num.langs` is `rowSums(part_langs[2:14])`.
i Input `num.langs` must be size 1, not 7.
i The error occurred in group 1: Participant.Private.ID = 5133249.真正奇怪的是,当我尝试创建这个问题的简化版以创建一个可再现的示例时,它工作得很好。
首先,我创建一个数据集。
test <- matrix(c(1, 1, 1, 0, 0, "",
2, 1, 0, 1, 0, "",
3, 0, 0, 0, 1, "Chinese"), ncol = 6, byrow=TRUE)
test<-as.data.frame(test)
colnames(test) <- c("ID", "English", "French", "Italian", "Other", "Other.Lang")
str(test)将二进制列转换为数字:
test$ID <- as.numeric(test$ID)
test$English <- as.numeric(test$English)
test$French <- as.numeric(test$French)
test$Italian <- as.numeric(test$Italian)
test$Other <- as.numeric(test$Other)这里有与上面相同的代码,但是使用了这个简化的数据集。
num <- test %>%
mutate(num.langs = rowSums(test[2:5]))
num这是输出。它完全符合我的要求:
"ID","English","French","Italian","Other","Other.Lang","num.langs"
1, 1, 1, 0, 0, "", 2
2, 1, 0, 1, 0, "", 2
3, 0, 0, 0, 1, "Chinese", 1所以我知道我在我的真实数据中搞砸了,但我不知道在哪里。有人能告诉我吗?
发布于 2021-11-25 16:35:09
结果上的差异可能是由于part_langs是一个分组数据,从文章中显示的str输出可以看出:
grouped_df [7 x 15] (S3: grouped_df/tbl_df/tbl/data.frame). 如果这是原因,那么首先ungroup并重新运行您的代码:
library(dplyr)
part_langs <- part_langs %>% ungroup发布于 2021-11-25 16:29:14
另一种更依赖dplyr的方法是使用rowwise和c_across
test %>%
rowwise() %>%
mutate(num.lang = sum(c_across(English:Other)))https://stackoverflow.com/questions/70114157
复制相似问题