0

I want to paste consecutive values in a dataframe into a new column in the same dataframe.

my dataframe is this:

x y
blue A234
green,black A5
yellow A6
blue,green,purple A7

I want to have a third column 'z', that will paste the values in 'x', like this:

x y z
blue A234 blue
green,black A5 blue,green,black
yellow A6 blue,green,black,yellow
blue,green,purple A7 blue,green,purple,blue,green,black,yellow
Johnson T
  • 27
  • 5

1 Answers1

1

In tidyverse, this can be done with accumulate and paste/str_c

library(dplyr)
library(purrr)
library(stringr)
df1 %>%
    mutate(z = accumulate(x, str_c, sep=","))

-output

#                x    y                                         z
#1              blue A234                                      blue
#2       green,black   A5                          blue,green,black
#3            yellow   A6                   blue,green,black,yellow
#4 blue,green,purple   A7 blue,green,black,yellow,blue,green,purple

Or a similar option with Reduce from base R

Reduce(function(...) paste(..., sep=","), df1$x, accumulate = TRUE)

data

df1 <- structure(list(x = c("blue", "green,black", "yellow", "blue,green,purple"
), y = c("A234", "A5", "A6", "A7")), class = "data.frame", row.names = c(NA, 
-4L))
akrun
  • 874,273
  • 37
  • 540
  • 662