我正在尝试按组国家和性别对最后3行唯一的串联标志
eg: for 1st row unique of flag -last 3 (i.e row1:row1) is "Yes" ,2nd row(row2:row1) is "Yes", for row 3 (i.e row3:row1) rows are No&Yes,..
country = c("US","US","US","US","US","US","US","US","US","US","US")
gender = c("M","M","M","M","M","F","F","F","F","F","F")
flag = c("Yes","Yes","No","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes")
i / p: df = data.frame(国家,性别,国旗)
o/p
flag_unique_concat = c("Yes","Yes","No,Yes","Yes,No","Yes","Yes","Yes","Yes","Yes","Yes","Yes")
required data set
df1<-cbind(df,flag_unique_concat)
答案 0 :(得分:2)
我们可以group_by
country
和gender
,使用rollapply
中的zoo
,我们可以将唯一的flag
粘贴在一起,窗口大小为3
library(dplyr)
library(zoo)
df %>%
group_by(country, gender) %>%
mutate(flag_unique_concat = rollapplyr(flag, 3,
function(x) toString(unique(x)), partial = TRUE))
# country gender flag flag_unique_concat
# <fct> <fct> <fct> <chr>
# 1 US M Yes Yes
# 2 US M Yes Yes
# 3 US M No Yes, No
# 4 US M Yes Yes, No
# 5 US M Yes No, Yes
# 6 US F Yes Yes
# 7 US F Yes Yes
# 8 US F Yes Yes
# 9 US F Yes Yes
#10 US F Yes Yes
#11 US F Yes Yes
答案 1 :(得分:0)
ave(df$flag, df$gender, df$country,
FUN = function(x){
sapply(seq_along(x), function(i){
toString(unique(x[max(i-2, 1):i]))
})
})
# [1] "Yes" "Yes" "Yes, No" "Yes, No" "No, Yes" "Yes" "Yes" "Yes"
# [9] "Yes" "Yes" "Yes"