【发布时间】:2021-11-25 16:05:12
【问题描述】:
我想获取参与者 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
所以我知道我在真实数据的某个地方搞砸了,但我不明白在哪里。有人可以建议吗?
【问题讨论】:
-
结果的差异可能是因为
part_langs是grouped_df [7 x 15] (S3: grouped_df/tbl_df/tbl/data.frame)。也许ungroup,像这样:library(dplyr); part_langs <- part_langs %>% ungroup? -
或者避免使用 mutate 并尝试
part_langs$num.langs = rowSums(part_langs[2:14]) -
@ChrisRuehlemann 你是对的!添加取消组合代码并再次运行它可以解决此问题。非常感谢!
-
@Dave2e 你是绝对正确的,这是迄今为止最明智的处理方法......但我很沮丧不知道为什么 mutate() 没有按照我想象的方式工作应该的,我必须先理解它。我也很欣赏你的建议。
-
如果有帮助,我将添加此评论作为回答,希望您能接受/支持它!