【发布时间】:2018-11-24 04:49:59
【问题描述】:
我有以下数据框(这是一个较大数据框的子集,具有 >3000 obs 和 2 个不同的年份):
rp.pptn <- data.frame(id = c("150015", "150016", "150017", "150018",
"150019", "150020"), year = structure(c(1L, 1L, 1L, 1L, 1L, 1L),
.Label = c("15", "18"), class = "factor"),
freqtools = c(1, 1, 2, 1, 1, 3), freqtrees = c(2, 3, 3, 5, 4, 3),
freqrt = c(2, 2, 2, 2, 1, 3), freqroamfriends = c(1, 1, 1, 3, 1, 1),
freqroamalone = c(1, 1, 1, 2, 1, 1), freqparts = c(2, 2, 2, 2, 3, 3),
freqmessy = c(5, 5, 2, 5, 4, 5), freqride = c(3, 1, 2, 5, 3, 3),
freqrain = c(1, 3, 2, 3, 1, 3))
我想count cols c(3:11) 中满足条件的值。我一直在尝试 rowSums,因为当我没有 id 或分组变量时,year、rowSums 实际上给了我这样的计数:
rp.pptn.no.id <- rp.pptn %>%
select(c(3:11)) %>%
mutate(pptnlow = rowSums(pptnrp == 1 | pptnrp == 2 | pptnrp == 6))
我还能够为选择列计算rowSums,如下所示:
rp.pptn <- rp.pptn %>%
mutate(pptnlow = rowSums(.[c(3:11)]))
但是,鉴于我需要 id 和 year 进行后续分析,我想一次性完成这两个步骤。我很想知道为什么,鉴于我的数据是数字的,rowSums 首先给我的是计数而不是总和。我实际上想要计数,即有多少列符合我的标准?
搜索让我认为基于此的某些东西可能会起作用:
rp.pptn <- rp.pptn %>%
mutate(pptnlow = rowSums(. [3:11]) %in% c(1, 2, 6))
这会返回一个逻辑向量 = FALSE,大概是因为我的条件没有得到满足。我不认为我错过了什么,但最终我想要的是下面的df:
rp.pptn <- data.frame(id = c("150015", "150016", "150017", "150018",
"150019", "150020"), year = structure(c(1L, 1L, 1L, 1L, 1L, 1L),
.Label = c("15", "18"), class = "factor"),
freqtools = c(1, 1, 2, 1, 1, 3), freqtrees = c(2, 3, 3, 5, 4, 3),
freqrt = c(2, 2, 2, 2, 1, 3), freqroamfriends = c(1, 1, 1, 3, 1, 1),
freqroamalone = c(1, 1, 1, 2, 1, 1), freqparts = c(2, 2, 2, 2, 3, 3),
freqmessy = c(5, 5, 2, 5, 4, 5), freqride = c(3, 1, 2, 5, 3, 3),
freqrain = c(1, 3, 2, 3, 1, 3), pptnlow = c(7, 6, 8, 4, 5, 2))
如前所述,我的实际数据集要大得多,因此自动化程度越高越好!谢谢。
【问题讨论】: