gpt4 book ai didi

R 中使用 Data.Table 滚动文本串联

转载 作者:行者123 更新时间:2023-12-02 11:00:59 25 4
gpt4 key购买 nike

我有一个如下所示的数据集:

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 和名称从前一列添加。新列的向量为:

rolltext<-c("a","ab","c","abd","abde","abdef","cg","cgh","cghi","cghij"

我现在不知道该怎么办。对于数字,我只会使用 cumsum 函数,但对于文本,我想我需要一个 for 循环或使用 apply 函数之一?

最佳答案

您可以将 Reduceaccumulate 选项结合使用:

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

或者,正如 @DavidArenburg 建议的那样,使用 sapply 构造每一行:

a[, rolltext := sapply(1:.N, function(x) paste(text[1:x], collapse = '')), by = name]
<小时/>

这是一个运行总和,而滚动总和(在OP的标题中)是不同的,至少在R语言中是这样。

关于R 中使用 Data.Table 滚动文本串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33456107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com