我有一个看起来像这样的数据框:
df = data.frame(animals = c("cat; dog; bird", "dog; bird", "bird"), sentences = c("the cat is brown; the dog is barking; the bird is green and blue", "the bird is yellow and blue", "the bird is blue"),year= c("2010","2012","2001"), stringsAsFactors = F)
df$year <- as.numeric(df$year)
> df
animals sentences year
1 cat; dog bird the cat is brown; the bird is green and blue 2010
2 dog; bird the dog is black; the bird is yellow and blue 2012
3 bird the bird is blue 2001
我想获得前5年(包括同年)内栏内动物的总数。
修改
例如:在第2行中,动物狗和鸟在前5年(包括同年)= 2012年在句子列中重复了3次:狗是黑色的; bird 是黄色和蓝色,而2010年: bird 是绿色和蓝色,总计SUM =3。
所需结果
# A tibble: 3 x 4
animals sentences year SUM
<chr> <chr> <dbl> <int>
1 cat; dog; bird the cat is brown; the bird is green and blue 2010 2
2 dog; bird the dog is black; the bird is yellow and blue 2012 3
3 bird the bird is blue 2001 1
解决方案
我使用了here中的以下代码,并添加了逻辑运算符:
animals[(year>=year-5) & (year<=year)]
,但它没有给我我想要的输出。我究竟做错了什么?
string <- unlist(str_split(df$sentences, ";"))
df %>% rowwise %>%
mutate(SUM = str_split(animals[(year>=year-5) & (year<=year)], "; ", simplify = T) %>%
map( ~ str_count(string, .)) %>%
unlist %>% sum)
任何帮助将不胜感激:)。
答案 0 :(得分:2)
尝试:
library(dplyr)
df %>%
mutate(SUM = sapply(strsplit(animals, "; "), length),
SUM = sapply(year, function(x) sum(SUM[between(year, x - 5 + 1, x)])))
这是输出:
animals sentences year SUM
1 cat; dog; bird the cat is brown; the dog is barking; the bird is green and blue 2010 3
2 dog; bird the dog is black; the bird is yellow and blue 2018 2
3 bird the bird is blue 2001 1
当然在2010
中,它与您所需的输出不对应,因为您之前没有提供数据。