How to loop and change multiple data frames in R

I have data frames A, B, C, ... and you want to change each data frame in the same way, for example. redefinition factors of factors that are present in all data frames:

A = data.frame( x=c('x','x','y','y','z','z') ) B = data.frame( x=c('x','y','z') ) C = data.frame( x=c('x','x','x','y','y','y','z','z','z') ) A$x = factor( A$x, levels=c('z','y','x') ) B$x = factor( B$x, levels=c('z','y','x') ) C$x = factor( C$x, levels=c('z','y','x') ) 

This becomes time consuming if there are many data frames and / or many changes. How can I do this briefly using a loop or something better? Direct approach e.g.

 for ( D in list( A, B, C ) ) { D$x = factor( D$x, levels=c('z','y','x') ) } 

does not work because it does not change the original data frames.

EDIT: Added definitions of A, B, and C to make it reproducible.

+4
loops r dataframe
source share
2 answers

One remark about R is that, in relation to, the assignment <- is transitive, while = - is not. So, if your data frames are anyway in this regard, you should do something like this:

 A$x <- B$x <- C$x <- factor( C$x, levels=c('z','y','x') ) 
+4
source share

If you don't need an explicit loop, you can use lapply:

 ll <- lapply( list(A, B, C), function(df) { df$x <- factor(df$x, levels=c('z', 'y', 'x')) return(df) } ) 

Since the data is copied only to you, you have to use the list returned from lapply.

Edit

 dfs <- list('A', 'B', 'C') levels <- c('z', 'y', 'x') l <- lapply( dfs, function(df) { # Get data frame by name df <- get(df) df$x <- factor(df$x, levels=levels) return(df) } ) for ( i in 1:length(dfs)) { assign(dfs[[i]], l[[i]]) } 
+2
source share

All Articles