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!
blist <- list(b1, b2, ... b12)blist[[4]]is the dataframeb4