Reputation: 197
I have several similarly named data frames in R. I am looking for a neat way to create a new column in each one of these data frames. The values in these columns should be dependent on the name of the data frame.
I have:
dfARCHIMEDES
var1 var2
a b
c d
dfPYTHAGORAS
var1 var2
e f
g h
And it should become:
dfARCHIMEDES
var1 var2 newvar
a b ARCHIMEDES
c d ARCHIMEDES
dfPYTHAGORAS
var1 var2 newvar
e f PYTHAGORAS
g h PYTHAGORAS
It goes without saying that if the data would have been this simple it would have been an easy task. However, I currently have about 250 data frames with 15 columns and 500 rows each.
I would be grateful for any help.
Upvotes: 0
Views: 39
Reputation: 319
You can get a vector with the names of all data frame in the global environment by doing:
library(dplyr)
df_names <-
sapply(.GlobalEnv, is.data.frame) %>%
which() %>%
names()
After that, a loop will do the trick:
for (i in df_names) {
assign(i, cbind(get(i), newvar = i))
}
Upvotes: 0
Reputation: 70643
You can approach this in the following manner. See comments in the code.
# make some sample data (which OP should provide...)
dfARCHIMEDES <- data.frame(var1 = c("a", "c"),
var2 = c("b", "d"))
dfPYTHAGORAS <- data.frame(var1 = c("e", "g"),
var2 = c("g", "h"))
# collect all object names that start with a "df" from your workspace
get.dfs <- ls(pattern ="^df")
# go through each data.frame
for (i in get.dfs) {
tmp <- get(i) # save the data.frame into a temporary variable
newname <- gsub("^df", "", i) # remove the df part from the name
tmp$newvar <- newname # create new variable with the new name
assign(i, tmp) # re-write the data.frame
}
> dfARCHIMEDES
var1 var2 newvar
1 a b ARCHIMEDES
2 c d ARCHIMEDES
> dfPYTHAGORAS
var1 var2 newvar
1 e g PYTHAGORAS
2 g h PYTHAGORAS
Upvotes: 2