Background
First I'll initialize some dummy dataframes (NOTE: in the real example there will be >40 dataframes):
colOne <- c(1,2,3)
colTwo <- c(6,5,4)
df_2004 <- data.frame(colOne,colTwo)
df_2005 <- data.frame(colTwo,colOne)
Problem
Now what I want to do is loop through every data frame in the workspace and add a column called year
to them, filled with 2004
if the suffix is _2004
and 2005
if the suffix is _2005
.
I can start by getting a list of all of the data frames in the workspace.
dfs <- ls()[sapply(ls(),function(t) is.data.frame(get(t)))]
dfs
[1] "df_2004" "df_2005"
But that's as far as I've managed to get.
Attempted Solution
This is what I tried:
for (d in dfs) {
d <- lapply(d, function(x){
t <- get(x)
if (grepl('2004',x)) {
t$year <- 2004
} else {
t$year <- 2005
}
t
})
}
This does not throw an error, but it doesn't do anything either other than set d
to "2005"
.
If I add a line print(t)
right before the line returning t
, I get this output in the console:
colOne colTwo year
1 1 6 2004
2 2 5 2004
3 3 4 2004
colTwo colOne year
1 6 1 2005
2 5 2 2005
3 4 3 2005
suggesting that the code gets through that part fine, because that's exactly what I want df_2004
and df_2005
to look like respectively. But df_2004
and df_2005
are not actually changed, which is what I want.