我想对指定的列执行rowSums()
.我的问题是,每一行需要求和的列是不同的,并且由另一个变量给出.其动机是判断给定列之前的三个值是否为NA.
可以通过以下方式构建示例数据框
toy <- data.frame(id = c(rep(1, 10), rep(2, 10), rep(3, 10)),
day = c(1:10, 1:10, 1:10),
response = c(1, NA, NA, NA, 1, 1, 1, NA, NA, 1,
1, 1, NA, 1 ,1 ,1 ,1 ,1 ,1, 1,
NA, 1, NA, 1, 1, 1, NA, NA, NA, NA),
colnum = c(rep(5, 10), rep(7, 10), rep(10, 10)))
toy <- toy %>% pivot_wider(names_from = 2, values_from = 3, names_prefix = "day")
toy
在本例中,变量colnum
给出了要判断前三天的日期.从数据来看,
toy
# A tibble: 3 x 12
id colnum day1 day2 day3 day4 day5 day6 day7 day8 day9 day10
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 5 1 NA NA NA 1 1 1 NA NA 1
2 2 7 1 1 NA 1 1 1 1 1 1 1
3 3 10 NA 1 NA 1 1 1 NA NA NA NA
我想在数据框中创建一个新列,其中ID 1、2和3的值分别为FALSE
、TRUE
和FALSE
.我们就叫它three_miss
吧.例如,对于id=1,我们想判断第2天到第4天是否都是NA,因为colnum=5.
我try 了一个简单的rowSums()实现
toy <- toy %>% mutate(three_miss = rowSums(select(., (colnum-1):(colnum+1)), na.rm = TRUE) == 3)
使用colnum-1:colnum+1
是根据我们需要的列号推断出来的.代码将运行,但three_miss
的所有值都为FALSE
,这不是正确或所需的输出.我收到警告消息:
There were 2 warnings in `mutate()`.
The first warning was:
i In argument: `three_miss = ==...`.
Caused by warning in `x:y`:
! numerical expression has 3 elements: only the first used
我从这里得到的感觉是,要么是select()
导致了问题,要么是rowSums()
每行产生了多个总和.我试着添加了group_by(id)
,但没有帮助.我希望停留在管道的环境中,但如果这不可能,我对其他解决方案持开放态度.
附注:我知道如果colnum
小于4或大于10可能会有问题.我正计划使用case_when()
来修正这一点.例如,
toy <- toy %>% mutate(three_miss =
case_when(
colnum <=3 ~ NA,
colnum > 10 ~ NA,
TRUE ~ code_that_works
)
)