Andrea
Andrea

Reputation: 7

For loop into a list with different dataframes

I have a list of 800 dataframes; they are very similar but different. The differences are the name of variables, and according to these differences there are two types of dataframes. Df type1 have Time Place Weather Df type2 have Place Weather Hours.

I want to make a conditioned for loop(s) for dataframes belonging to type1 and type2, like in the example commented below.

myList = replicate(n = 400,
                     expr = {data.frame(Place = c("Milan", "Rome", "Naples"),
                                        Weather = c("Hot-Wet", "Hot-SemiWet", "Hot-Windy"),
                                        Month = c("June", "June", "June"))},
                     simplify = F)
add = replicate(n = 400,
                expr = {data.frame(Time = c("June", "June", "June"),
                                   Place = c("Milan", "Rome", "Naples"),
                                   Weather = c("Hot-Wet", "Hot-SemiWet", "Hot-Windy"))},
                simplify = F)
myList <- c(myList, add)

for(i in 1:length(myList) {
    if( # if df has a variable = Time,
       do nothing)
    else( # else df has a variable = Month,
         myList[[i]] <- rename(myList[[i]], Time = Month)
}

Upvotes: 0

Views: 29

Answers (1)

Wimpel
Wimpel

Reputation: 27792

Since you are working with a list, lapply() should be the first function to consider (in stead of a for-loop).

There is no need for the if-else statement, if you use the any_of-selector.

What the code below functionally does:

  1. loop over myList
  2. check if any of the columns in the current list's element is named "Time"
  3. if so, rename the column from "Time" to "Month"

code

library(dplyr)
#create a named vector for the columns you want to rename
rename.v <- c(Month = "Time")
# loop the list, replace the columns if they exist
myNewList <- lapply(myList, rename, any_of(rename.v))

Upvotes: 0

Related Questions