Reputation: 678
I have a list of data frames, each named according to type. All dataframes have the same column names. I want to apply the name of each data frame to one specific column in that data frame.
df1 <- data.frame(var_a = 1, var_b = 2, var_X = 3)
df2 <- data.frame(var_a = 4, var_b = 5, var_X = 6)
types <- c("typeA", "typeB")
lst <- list(df1, df2)
names(lst) <- types
This gives me:
> lst
$typeA
var_a var_b var_X
1 1 2 3
$typeB
var_a var_b var_X
1 4 5 6
What I want it to change var_x
in each data frame to the respective type.
I tried looping over the elements in types
to using this to subset to the respective list item:
for (i in types) {
colomnnames <- c("var_a", "var_b", types[i])
colnames(lst[[i]]) <- colomnnames
}
This, however, changes the name of the last columns to NA
. What am I missing?
Upvotes: 0
Views: 30
Reputation: 523
The issue you have is in the for loop at this line:
colomnnames <- c("var_a", "var_b", types[i])
change it to:
colomnnames <- c("var_a", "var_b", i)
Upvotes: 1