0

Consider a list of tibbles tib_list: tib1, tib2, tib3, etc.

I would like to use lapply to change the names of each tibble to tib1_new, tib2_new, tib3_new, etc.

Something along the lines of this.

lapply(tib_list, "..."_new <- "...")

ie)

tib1_new <- tib1

for the entire list

So the output is tib1_new, tib2_new, tib3_new, etc.

1 Answers1

1

It's a little unclear what format the data is currently in. As others suggested, you could put the tibbles into a nested list then rename them with lapply. If you have the tibbles already in your global environment, then you can do something like this to get them into a list. However, if you have the data in .csv, then it's much easier to put these in a list when you read them in as @GregorThomas linked to.

set.seed(232)
tib1 <- data.frame(replicate(10,sample(0:1,5,rep=TRUE)))
tib2 <- data.frame(replicate(10,sample(0:1,5,rep=TRUE)))
tib3 <- data.frame(replicate(10,sample(0:1,5,rep=TRUE)))

Pattern1 <- ls(pattern = "tib")
Pattern1_list <- mget(Pattern1)

# To be able to use lapply, it needs to be nested.
Pattern1_list_new <- list(Pattern1_list)

Pattern1_list_new <- lapply(
  Pattern1_list_new,
  plyr::rename,
  c(
    "tib1" = "tib1_new",
    "tib2" = "tib2_new",
    "tib3" =  "tib3_new"
  )
)

# Then you could unnest one level to get just the list of dataframes.
Pattern1_list_new <- unlist(Pattern1_list_new,recursive=FALSE)

Output

names(Pattern1_list)

[1] "tib1_new" "tib2_new" "tib3_new"

However, instead of using lapply, you could just apply the names directly to the list of dataframes.

names(Pattern1_list) <- c("tib1_new", "tib2_new", "tib3_new")
AndrewGB
  • 16,126
  • 5
  • 18
  • 49