且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R通过追加列合并重复的行

更新时间:2023-12-01 13:29:28

您需要创建一个变量以用作列中的数字. rowid(comment)可以解决问题.

You need to create a variable to use as the numbers in the columns. rowid(comment) does the trick.

在dcast中,将行标识符放在~的左侧,将列标识符放在右侧.然后,value.var是要包含在此从长到宽转换中的所有列的字符向量.

In dcast you put the row identifiers to the left of ~ and the column identifiers to the right. Then value.var is a character vector of all columns you want to include int this long-to-wide transformation.

library(data.table)
setDT(df)

dcast(df, comment ~ rowid(comment), value.var = c('sentiment', 'tone'))

#     comment sentiment_1 sentiment_2 sentiment_3 tone_1 tone_2 tone_3
# 1: commentA           1           4           1      1      2      6
# 2: commentB           2           1          NA      5      3     NA
# 3: commentC           2          NA          NA      1     NA     NA