Home > database >  Selector within an lapply function in R
Selector within an lapply function in R

Time:07-12

I am repeating a function in R to perform a computation, but have encountered an issue with the code to repeat it. When I perform the function on an individual file, there is no error, however when I attempt to repeat it/automate it, it yields the following error:

$ operator is invalid for atomic vectors

My code is essentially the following:

listed_dataframes <- list("df1", "df2", "df3")

results <- lapply(listed_dataframes, function(file) {
mutate(V2 = ifelse(file$V1 == 'a', TRUE, FALSE)) %>% 
summarise(share = mean(V2))})

Summarise poses no issue, but the error emerges seemingly with the use of the selector $ on V1 (variable one). V1 is obviously a variable of all the dataframes.

I also tried adding file %>% before the mutate but this only produced a new error: no applicable method for 'mutate' applied to an object of class "character"

I need to run the code to repeat the piped function on all the dataframes. Can the selector not be used within an lapply function? If not, how can I alternatively automate this process and select the right variable within every distinct dataframe.

CodePudding user response:

Let me know if this works:

listed_dataframes <- list("df1", "df2", "df3")

results <- lapply(listed_dataframes, function(file) {
mutate(file, V2 = if_else(V1 == 'a', TRUE, FALSE)) %>% 
summarise(share = mean(V2))})

CodePudding user response:

Try this

listed_dataframes <- list("df1", "df2", "df3")

results <- lapply(listed_dataframes, function(file) {
mutate(get(file) , V2 = ifelse(V1 == 'a', TRUE, FALSE)) %>% 
summarise(share = mean(V2))})

  • Related