连接一列的级别并合并另一列的值

Concatenating levels of one column and merging the values of another column

我有一列具有共同水平的代表 (1-4)。我在 col3 中有与他们一起使用的数据。有些级别不包含信息,但对于包含信息的级别,我想将值按 col1 中的每个公共级别合并到一列中。 col3 中的值不一致。

我尝试删除重复项,但这不会合并 col3 值。

train <- data.table(col1=c(rep('a0001',4),rep('b0002',4)), col2=c(seq(1,4,1),seq(1,4,1)), col3=c("12 43 543 1232 43 543", "","","","15 24 85 64 85 25 46","","658 1568 12 584 15684",""))

这是可重现的代码 我有大约 40000 行要做。

result<-data.frame(col1=c("a0001","b0002"),col3=c("12 43 543 1232 43 543",'15 24 85 64 85 25 46 658 1568 12 584 15684'))

这就是我要找的结果...

我们可以将 col3 值带入 separate_rows,删除空值,group_by col1paste col3 值一起。

library(dplyr)

train %>%
   tidyr::separate_rows(col3) %>%
   filter(col3 != '') %>%
   group_by(col1) %>%
   summarise(col3 = paste(col3, collapse = " "))

# col1  col3                                      
#  <chr> <chr>                                     
#1 a0001 12 43 543 1232 43 543                     
#2 b0002 15 24 85 64 85 25 46 658 1568 12 584 15684

我正在学习@Ronak Shah 的回答。这可能是一个变体:

library(dplyr)
train %>% group_by(col1) %>% summarise(col3 = paste(col3, collapse = " "))

  col1  col3                                          
  <chr> <chr>                                         
1 a0001 "12 43 543 1232 43 543   "                    
2 b0002 "15 24 85 64 85 25 46  658 1568 12 584 15684 "