通过在R中连接来分组

时间:2016-02-11 16:21:09

标签: r

我的数据框有两百万的观察结果。

数据样本如下表所示。

Pid Feature     Value
1   color       Red
1   size        10
1   weight      High
2   angle       90
2   temperature It works with low temperature
2   wheel       No
3   dimensions  23ft x 23 ft

我想在以下数据框中连接feature列表及其value

Pid  Feature_list               Values
1   color, size, weight         Red, 10, High
2   angle, temperature, wheel   90, it works with low temperature, No
3   dimensions                  23ft x 23 ft

我在R中使用了foreachpaste命令。以下是我使用的代码示例。

 foreach( #all products# ) %dopar%
   {
  ... 
    feature_sum <- rbind(feature_sum,pid , paste(att[att$id==pid,][2][,], collapse = " "), paste(att[att$pid==pid,][3][,], collapse = " ")))

  }

但问题是根据所需格式处理数据需要很长时间。

有没有办法加快处理速度?或者我可以避免foreach循环吗?

1 个答案:

答案 0 :(得分:2)

我们可以使用data.table

library(data.table)
setDT(df1)[ ,lapply(.SD, toString) , by = Pid]