Execute the same operation for few variables

I want to know if it's possible by giving a list of variable to execute the same operation for differents variables

For example, instead of this :


doing something like this :

for each in list of var do : listOfVar<-base$listOfVar

I write it like this to illlustrate because I have no idea of how to do that. Thank you for your time

Don't know if I get it correctly, you can use map() function from purrr package to easily apply same treatment to every vars from a list/dataframe.

for example


mtcars %>% map(~.x *10)

will multiply all numbers from all vars in the table mtcars by ten, and returning a list.

in your case, you can do either simply unlist(base)to get a list consisted of variables from base

or base %>% map(~ .x) to get the same result.

or if you're actually want to store vars from a list by their name, you can use function assign() from base R, in your case, it's like:

for (i in names(base)) assign(i,base[i])

I tried this

for (i in names(base)) assign(i,base[i])

but instead of few values, it gaves me few dataframes of one variable

Its hard to know how to advise you and fight the fear that we'd be moving you away from good practice to less-good as your ask seems rather vague, it seems like you are asking how to perform an interim step of a larger goal. I believe if we had sight of your larger goal, or typical usecase you wish to address, then the quality of advice we could give you would be greater.

There are extremely convenient ways to work with variables of a dataframe and for example execute the same operation over a few of its variables, therefore can you justify why breaking them out into an an explicit list would seem to be a worthwhile part of your process ?

1 Like

oh, I guess you should use double brackets for list objects, i.e.:

for (i in names(base)) assign(i,base[[i]])

I saw your message from another topic, but when I finish typing, the original message was deleted, here're my reply to that:

for this situation, it's not that easy to apply a treatment to multiple global-environment variables, I suggest you pre-process the original list then transfer them into vars.

map() is a traversal function from purrr package which can apply a function to each element of a list or atomic vector. In your case, you can try:

base <- base %>% map(
    ~ .x %>% mutate(
        across(where(is.numeric),  ~ replace_na(.x, 0)),
        across(where(is.character),  ~ replace_na(.x, ""))
# replace_na() will return same datatype as input, so you can't pass "" to a numeric nor 0 to a character
# then :
for (i in names(base)) assign(i,base[[i]])

hope it can help!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.