0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Would this work for a much more involved set of manipulations than just taking the head? I'm still not familiar with lapply, sapply, etc..
yes it would... lapply(mylist, function(x) { ... whatever you want to do with element x .. }) would work
Even multiple steps, e.g., take rows which meet a certain condition, mutate to create new column based on another column, gather the result, etc. ?
sure.. I can't see why not. Just remember that the last line defines the output, or use return().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.