我有一个有四列的数据框。
country date pangolin_lineage n cum_country
1 Albania 2020-09-05 B.1.236 1 1
2 Algeria 2020-03-02 B.1 2 2
3 Algeria 2020-03-08 B.1 1 3
4 Algeria 2020-06-09 B.1.1.119 1 4
5 Algeria 2020-06-15 B.1 1 5
6 Algeria 2020-06-15 B.1.36 1 6我希望计算国家和日期之间n的累积和。我可以用下面的代码做到这一点:
date_country$cum_country <- as.numeric(unlist(tapply(date_country$n, date_country$country, cumsum)))然而,我现在想要做同样的事情,但是在国家、pangolin_lineage和日期之间的累积和。我尝试在上面的函数中添加另一个向量,但似乎您只能为tapply输入一个索引输入和一个向量输入。我得到了这个错误:
date_country$cum_country_pangol <- as.numeric(unlist(tapply(date_country$n, date_country$country, date_country$pangolin_lineage, cumsum)))
Error in match.fun(FUN) :
'date_country$pangolin_lineage' is not a function, character or symbol有谁知道如何在多个向量(country,pangolin_lineage,date )中使用cumsum?
发布于 2021-03-04 00:54:15
如果有多个组,则将其包装在一个函数中,但请注意,在汇总函数中tapply,当我们指定像cumsum这样的函数时,它可能会被拆分。
tapply(date_country$n, list(date_country$country, date_country$pangolin_lineage), cumsum))但是,使用ave要简单得多,也就是说,如果我们想创建一个新列,只需使用ave就可以避免unlist等的麻烦
ave(date_country$n, date_country$country,
date_country$pangolin_lineage, FUN = cumsum)
#[1] 1 2 3 1 4 1https://stackoverflow.com/questions/66461437
复制相似问题