跟进:R中有没有办法在定义的连续行上制作ifelse?
数据:
df<-data.frame(group=c(1, 1,1, 1,1, 2, 2, 2, 4,4,4,4),
value=c("A","B","C","B","A","A","A","B","D","A","A","B"),
want_every_c=c("yes","yes","yes","yes","yes","no","no","no","no","no","no","no"),
want_every_b=c("yes","yes","yes","yes","yes","yes","yes","yes","no","no","no","no"),
want_two_a_within_together=c("no","no","no","no","no", "yes","yes","yes", "yes","yes","yes", "yes" ))
这些解决方案非常适合在扫描三个列时获得"want_every_"列。
以前的解决方案:
f2 <- function(colNm, val){
c('no', 'yes')[(all(rollapply({{colNm}}, 3,
FUN = function(x) val %in% x))) + 1]
}
df %>%
group_by(group) %>%
mutate(want_every_c = f2(value, "C"),
want_every_b = f2(value, "B"))
我是函数的新手,想以不同的方式使用它。我想要一个名为"want_two_a_within_together"的新列,在一个组中,任何两个扫描都是完全值='A'。这样:
group value want_two_a_within_together
1 1 A no
2 1 B no
3 1 C no
4 1 B no
5 1 A no
6 2 A yes
7 2 A yes
8 2 B yes
9 4 D yes
10 4 A yes
11 4 A yes
12 4 B yes
我想我可以在函数中的某处添加"any"并将宽度更改为 2,但不完全确定。
制作窗口 3 时的当前尝试和问题:
f2 <- function(colNm, val, w){ c('no', 'yes')[(all(rowSums(rollapply({{colNm}}, w, FUN = function(x) x %in% val)) > 0))+1]}
df<-data.frame(value=c("B","B","B","B","B","A","A","A","A","A","A"),
correct=c("yes","yes","yes", "yes","yes","yes", "yes" ,"yes","yes","yes","yes"))
df%>% mutate(try = if(n()>2) f2(value, "A", 3) else "no")
value want_three_a_within_together try
1 B yes no
2 B yes no
3 B yes no
4 B yes no
5 B yes no
6 A yes no
7 A yes no
8 A yes no
9 A yes no
10 A yes no
11 A yes no
可以修改该函数以计算rowSums
f2n <- function(colNm, val, w){
c('no', 'yes')[(any(rowSums(rollapply({{colNm}}, w,
FUN = function(x) x %in% val)) == w))+1]
}
library(dplyr)
library(zoo)
df%>%
group_by(group) %>%
mutate(new_want_two_a_within_together = if(n()>1) f2n(value, "A", 2) else "no")
# A tibble: 18 x 4
# Groups: group [4]
# group value want_two_a_within_together new_want_two_a_within_together
# <dbl> <fct> <fct> <chr>
# 1 1 A no no
# 2 1 B no no
# 3 1 C no no
# 4 1 B no no
# 5 1 A no no
# 6 2 A yes yes
# 7 2 A yes yes
# 8 2 B yes yes
# 9 4 D yes yes
#10 4 A yes yes
#11 4 A yes yes
#12 4 B yes yes
#13 5 A yes yes
#14 5 B yes yes
#15 5 B yes yes
#16 5 A yes yes
#17 5 A yes yes
#18 5 A yes yes