BOBjwjwj3j3j
BOBjwjwj3j3j

Reputation: 141

iterate over a set of dataframes in R

Let's say I have a set of dataframes: df1, df2, d3, df4. I want to apply some sort of behaviour over each of these dataframes. Rather than copying the code repeatedly, I want to do this through some sort of for loop. For example, let's say I want to take the df and re assign it so that the first column is row names. The normal way I'd do this is:

df1_b <- df1[,-1]
rownames(df1_b) <- df1[,1]

How would I go about doing this to all four dataframes that I have. I imagine I'd need to somehow make group the dataframes into a single set and then do something like

for (i in set) {
  i+"_b" <- i[,-1]
  rownames(i_b) <- i[,1]
}

I tried to do this with a cbind:

df_set <- c(df1, df2, df3, df4)
for (i in df_set) {
  i+"_b" <- i[,-1]
  rownames(i_b) <- i[,1]
}

But of course that didn't work (I'm pretty sure R does not do string concatenation like this).

Any help would be appreciated!

Upvotes: 3

Views: 294

Answers (2)

akrun
akrun

Reputation: 887821

We can use mget to get the values of the multiple objects into a list and then do the processing in the list by looping over the list with lapply

lst1 <- lapply(mget(paste0("df", 1:4)), function(x) {
               row.names(x) <- x[,1]
                x[,-1]
    })

If we want to change the original objects (not recommended)

list2env(lst1, .GlobalEnv)

Or another option is tidyverse

library(purrr)
library(tibble)
library(dplyr)
mget(ls(pattern = "^df\\d+$")) %>%
     map(~ .x %>%
               column_to_rownames(names(.)[1])) 

Upvotes: 3

Jakub.Novotny
Jakub.Novotny

Reputation: 3067

You can apply a function this way for example:

# getting some dummy data
df1 <- mtcars
df2 <- mtcars
df3 <- mtcars
df4 <- mtcars

lst <- list(df1, df2, df3, df4)

# example of applying the function row.names to the data
Map(row.names, lst)

Upvotes: 2

Related Questions