How do I add a suffix (or prefix) elements of an existing list?

Viewed 7389

Let's say I have an existing list called myList.

myList <- list(list1=c("item1", "item2"), list2=c("item3", "item4"))

myList thus contains:

$list1
[1] "item1" "item2"

$list2
[1] "item3" "item4"

I want to append .t0 to each element of list1 and list2 within myList so I end up with:

$list1
[1] "item1.t0" "item2.t0"

$list2
[1] "item3.t0" "item4.t0"

I do not want to go back to the list(list1=c("item1", "item2"), list2=c("item3", "item4")) step and add .t0 there. I want to manipulate myList to add .t0.

3 Answers

I wanted to add an answer if you have a column in dataframe format since the other answers don't work for that situation as written.

library(tidyverse)
myList <- data_frame(list1=c("item1", "item2"), list2=c("item3", "item4"))
myList <- myList %>% 
  mutate(
    list1 = paste0(list1, ".t0"),
    list2 = paste0(list2, ".t0")
  )

This is best if you only have a few columns. You could likely use map to iterate through multiple columns.

Related