Reputation: 2297
I have a list of dfs lst
, and each df in lst
have variable "ID". It is possible to set "ID" as a factor at once, in stead of set one by one?
Is this called setting up a variable in global environment? I might used the wrong term.
Upvotes: 1
Views: 87
Reputation: 9858
You can also use the tidyverse
:
library(purrr)
library(dplyr)
map(lst, ~.x%>%mutate(ID=as.factor(ID))
an example with the iris dataset:
#first transform the Species into a character variable:
iris<-iris%>%mutate(Species=as.character(Species))
#second, create an additional iris dataframe for the list
iris2<-iris
lst<-list(df1=iris, df2=iris2)
#Then call map with the mutating function:
map(lst, ~.x%>%mutate(Species=as.factor(Species)))
Upvotes: 2
Reputation: 887158
We can loop over the list
with lapply
, and transform
lst <- lapply(lst, transform, ID = factor(ID))
Or if we have an object with string 'ID' in the global env
v1 <- "ID"
lst <- lapply(lst, function(x) {
x[[v1]] <- factor(x[[v1]])
x})
Upvotes: 1