I want to do the same manipulation to each element in a list of data frames using a for loop. I then want to assign the name of these using the original name of the element. I'd like to know how to do this in the case where I just reassign with the same name, or assign with the old name with a suffix or prefix.
I can do it by adding new names with paste0, for example:
# load example data frames and add to list
data("iris")
data("cars")
list_df <- list(iris, cars)
# create new list for manipulated data frames. Using head() as an example.
list_head < - list()
# for loop to take head of each data frame in list_df, assign iterative name and add to list_head
for (i in 1:length(list_df){
temp <- head(list_df[[i]])
new_list[[paste0("df_head",i)]] <- temp
}
I want to be able to assign a variable within a loop based on the iteration, where the names assigned are the same as the old names, and/or with the old name plus a suffix/prefix, e.g. "cars_head". The adding to a list part isn't important, although if that can be done straightforwardly as well that would be great.
CodePudding user response:
I think this is a more R-like approach...
data("iris")
data("cars")
library(tibble)
#create a list with names of the elements
list_df <- tibble::lst(iris, cars)
#get head of list's elements
new_list <- lapply(list_df, head)
#new names
names(new_list) <- paste0(names(list_df), "_head")
new_list
# $iris_head
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
#
# $cars_head
# speed dist
# 1 4 2
# 2 4 10
# 3 7 4
# 4 7 22
# 5 8 16
# 6 9 10