简体   繁体   中英

How to combine values in column B based on values in Column A using R?

I'm trying to combine values in Item.ID column below based on ID value in ID column, the values in the Item.ID column can be seperated using a comma:

Dataframe (AS):

AS <- data.frame("Index" = c(1,1,2,2,2,3,4), "Item.ID" = c("A1","C2","A3","U4","M5","K6","Y9"))

Required Output

AS_Wide <- data.frame("Index" = c(1,2,3,4), "Item.ID" = c("A1,C2","A3,U4,M5","K6","Y9"))

Using base R, with just aggregate and paste :

AS.Wide <- aggregate(AS$Item.ID, by=list(Index=AS$Index), paste, collapse=",")

If you want to keep the "Item.ID" variable name, you will need to change it:

names(AS.Wide)[2] <- "Item.ID"

Using Tidyverse/dplyr:

Group by Index,

Arrange them by Item.ID as well so the result is alphabetized but that is up to you.

paste all the Item.ID's together by collapsing them with a ",".

library(dplyr)
AS_Wide <- AS %>% 
  group_by(Index) %>% 
  arrange(Item.ID) %>% 
  summarize(Item.ID = paste(Item.ID, collapse = ","))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM