rlistiteration

Looping over a list but using names instead of the actual objects


I am trying to use lapply to apply a function to some dataframes. I have a list containing the names of the dataframes I want to use. The problem is, that when I use lapply on the list it gives me an error because it's trying to apply the function to the character vector rather than the objects. If possible, I'd like to stay in base R (no rlang etc.)

Thank you for help!

Example:

#using dataset iris included in R
data1 <- iris
data2 <- iris
data3 <- iris

list1<-c("data1","data2","data3")

print_func<-function(x){
print(x[1,1]) #print the first object of each dataframe
}

lapply(list1,print_func)


Error in x[1, 1] : incorrect number of dimensions 

 
print_func(data1)
[1] 5.1 # works because its evaluating the list obj

Solution

  • You may want to use mget.

    > mget(c("data1","data2","data3")) |> lapply(print_func)
    [1] 5.1
    [1] 5.1
    [1] 5.1
    $data1
    [1] 5.1
    
    $data2
    [1] 5.1
    
    $data3
    [1] 5.1