R 将列的所有先前元素粘贴为得分最高的行

R 将列的所有先前元素粘贴为得分最高的行,r,data.table,concatenation,paste,R,Data.table,Concatenation,Paste,这就是我的数据框的外观: library(data.table) dt <- fread(' Product Score Description A 1 aapl A 2 banana A 3 orange B 1 coke B 2 pepsi C

这就是我的数据框的外观:

library(data.table)
dt <- fread('
    Product   Score    Description
    A          1         aapl 
    A          2         banana 
    A          3         orange
    B          1         coke
    B          2         pepsi
    C          1         butter
    D          1         milk 
')
我试过了

    dt[,Description2 := as.character(ifelse(!max(Score),NA,paste(shift(Description,1),
Description,sep=";"))),by=Product]

谢谢你的帮助

我们按“产品”分组,获得“分数”的
max
,并
粘贴
collapse=“;”
一起的“说明”



使用
:=
(赋值)在初始数据集中创建一个新列。对于总结,我们可以将其保存在
列表中
,或者在按变量分组后使用
)。

谢谢您的回答!产品前面的时段的用途是什么。(产品)?@gibbz00没有这个必要。您可以只使用
by=Product
。但是,如果您有多个分组变量,我将其用于一般用途。否则,它就是
by=list(Product)
    dt[,Description2 := as.character(ifelse(!max(Score),NA,paste(shift(Description,1),
Description,sep=";"))),by=Product]
dt[, .(ScoreMax = max(Score), Description2 = paste(Description, collapse=";")), 
          by = .(Product)]
#   Product ScoreMax       Description2
#1:       A        3 aapl;banana;orange
#2:       B        2         coke;pepsi
#3:       C        1             butter
#4:       D        1               milk