我有一个如下所示的数据集:
rownum<-c(1,2,3,4,5,6,7,8,9,10)
name<-c("jeff","jeff","mary","jeff","jeff","jeff","mary","mary","mary","mary")
text<-c("a","b","c","d","e","f","g","h","i","j")
a<-data.table(rownum,name,text)
我想添加一个新的文本列,该列由rownum和name从前一列添加。新列的向量是:
rolltext<-c("a","ab","c","abd","abde","abdef","cg","cgh","cghi","cghij"
我在这里做什么都不知所措。对于数字我只会使用cumsum函数,但对于文本我认为我需要一个for循环或使用其中一个apply函数?
答案 0 :(得分:7)
您可以将$(document).on('click', '.hb-menu-btn', function(){
$('.hb-menu-btn, .hb-menu, .hb-menu-page').toggleClass('hb-menu-open');
});
与Reduce
选项一起使用:
accumulate
或者,正如@DavidArenburg建议的那样,使用a[, rolltext := Reduce(paste0, text, accumulate = TRUE), by = name]
rownum name text rolltext
1: 1 jeff a a
2: 2 jeff b ab
3: 3 mary c c
4: 4 jeff d abd
5: 5 jeff e abde
6: 6 jeff f abdef
7: 7 mary g cg
8: 8 mary h cgh
9: 9 mary i cghi
10: 10 mary j cghij
构建每一行:
sapply
这是正在运行的总和,而滚动总和(在OP的标题中)是不同的,至少在R lingo中。
答案 1 :(得分:7)
这是一个使用substring()
的想法。
a[, rolltext := substring(paste(text, collapse = ""), 1, 1:.N), by = name]
给出了
rownum name text rolltext
1: 1 jeff a a
2: 2 jeff b ab
3: 3 mary c c
4: 4 jeff d abd
5: 5 jeff e abde
6: 6 jeff f abdef
7: 7 mary g cg
8: 8 mary h cgh
9: 9 mary i cghi
10: 10 mary j cghij
我们或许可以使用 stringi 包
加快速度library(stringi)
a[, rolltext := stri_sub(stri_c(text, collapse = ""), length = 1:.N), by = name]