Home > Back-end >  How to append the beginning and end of a string to every item in a list in a R dataframe
How to append the beginning and end of a string to every item in a list in a R dataframe

Time:07-15

I have a column in my dataframe that contains a list in each row. I need to take every item in these lists and append, to the beginning of each item in the list, the first three characters of a string in the same row but in a separate column. I then need to append the last three characters of that string to the end of each item in the list.

For example, for this dataframe:

tester <- data.frame(id = c(123456789, 987654321)) tester$furniture <- list(c("chair", "couch"), c("bed", "bench"))

The desired output would be, in a new column in the dataframe:

tester$output <- list(c("123chair789", "123couch789"), c("987bed321", "987bench321"))

Any help would be greatly appreciated. Thanks so much!

CodePudding user response:

tester<-data.frame(id=c(123456789,987654321)) 
tester$furniture<-list(c("chair","couch"),c("bed","bench"))
tester$output<-list(c("123chair789","123couch789"),c("987bed321","987bench321"))
tester$output1<-c(toString(paste0(substr(tester$id,1,3),tester$furniture[[1]],substr(tester$id,7,9))),
                  toString(paste0(substr(tester$id,1,3),tester$furniture[[2]],substr(tester$id,7,9))))

CodePudding user response:

library(dplyr)
library(tidyverse)

tester <- data.frame(id = c(123456789, 987654321))
tester$furniture <-  list(c("chair", "couch"), c("bed", "bench"))

tester1 <- tester %>% 
  unnest(furniture) %>% 
  rowwise() %>% 
  mutate(output = sapply(furniture, function(x) paste(substr(id, 1, 3), x, substr(id, nchar(id)-3 1, nchar(id)), sep = "")))

attr(tester1$output, "names") <- NULL

tester1 <- tester1%>% 
  group_by(id) %>% 
  summarise(furniture = list(furniture),
            ouput = list(output))

enter image description here

  • Related