solaris92
solaris92

Reputation: 21

Using loop in a name of dataframe

I am very new in R, and I would be very grateful for any help!

I have created 12 dataframes, named b1, b2, ... b12. Now in each of the dataframes I want to create a variable "Orig" indicating a number of the dataframe.

In other words, I want to write a loop which does the same as this code:

b1$Orig <- 1
b2$Orig <- 2
...
b12$Orig <- 12

or as this one:

b1 <- b1 %>%
  mutate(Orig = 1)
...
b12 <- b12 %>%
  mutate(Orig = 12)

I have tried this:

for (i in 1:n){
  paste0("b", as.character(i))[[Orig]] <- i
  }

But get an error:

Error in paste0("b", as.character(i))[[Orig]] <- i : target of assignment expands to non-language object

So I guess I need to create a vector Orig first in the loop, but <i dont know how.

I have also tried this:

for (i in 1:n){
  assign (paste0("b", as.character(i)), paste0("b", as.character(i)) %>% mutate(Orig = i))
  }

But get an error:

Error in UseMethod("mutate") : no applicable method for 'mutate' applied to an object of class "character"

Here I have tried to use as.data.frame function

for (i in 1:n){
  assign (paste0("b", as.character(i)), as.data.frame(paste0("b", as.character(i))) %>% mutate(Orig = i))
  }

, but as result I get only (1x1) dataframes with a single number.

I wonder what else could I do? Thanks a lot!

Upvotes: 2

Views: 70

Answers (1)

dcarlson
dcarlson

Reputation: 11046

Let's create a simple example:

b1 <- data.frame(a=1:4, b=5:8)
B <- list(b1, b2, b3, b4)

Now to add the Orig column use lapply

B2 <- lapply(1:4, function(x) data.frame(Orig=x, B[[x]]))
B2
# [[1]]
#   Orig a b
# 1    1 1 5
# 2    1 2 6
# 3    1 3 7
# 4    1 4 8
# 
# . . . .
# 
# [[4]]
#   Orig a b
# 1    4 1 5
# 2    4 2 6
# 3    4 3 7
# 4    4 4 8

If you now want to combine the labeled data frames into a single one:

B3 <- do.call(rbind, B2)

Upvotes: 1

Related Questions