0

i am trying to concatenate all values with unique column value by pivoting the data frame

var = c("X","X","Y","Z","Z","Z")
value =c(1,4,7,21,3,45)
df = data.frame(var,value)

o/p

df1
var    value
X      (1),(4)
Y      (7)
Z      (21),(3),(45)

Thanks in advance

suny
  • 119
  • 9

3 Answers3

1

With dplyr

df %>%
  mutate(value = paste0("(",value,")")) %>%
  group_by(var) %>%
  summarise_at(vars(value), paste, collapse = ",")
hpesoj626
  • 3,529
  • 1
  • 17
  • 25
0

We can use aggregate with c:

aggregate(value ~ var, data = df, c)

  var     value
1   X      1, 4
2   Y         7
3   Z 21, 3, 45
LAP
  • 6,605
  • 2
  • 15
  • 28
0

you can split the dataset and do whathever you want with the value series:

var = c("X","X","Y","Z","Z","Z")
value =c(1,4,7,21,3,45)
df = data.frame(var,value)

dflist <- split(df, df$var)

sapply(dflist, function(x) paste(x$value, collapse = ","))

result:

    X         Y         Z 
"1,4"       "7" "21,3,45" 
Wietze314
  • 5,942
  • 2
  • 21
  • 40