Reputation: 3
I have a list with several dataframes, each dataframe correspond to an election, say 2010, 2013, ..., 2021.
For each dataframe, I want to add the year to every column name except the first three columns. So I'm trying to add the year to [,4:end_column] using a for loop:
for (i in names(SECCIONES_year)) {
year <- (substr(i, nchar(i)-4, nchar(i)))
end_column <- ncol(SECCIONES_year[[i]])
past_names <- names(SECCIONES_year[[i]][ ,4:end_column])
colnames(SECCIONES_year[[i]][,4:end_column]) <- paste(past_names, year, sep="")
}
Unfortunately, it doesn't work but it does if I work with all column names as:
colnames(SECCIONES_year[[i]]) <- paste(past_names, year, sep=)
I tried with colnames, names and setNames but failed every try.
Upvotes: 0
Views: 73
Reputation: 309
Theres no need for comma in the second bracket, before "4":
colnames(SECCIONES_year[[i]])[4:ncol(SECCIONES_year[[i]])] <- paste(past_names, year, sep="")
Upvotes: 0
Reputation: 886938
With base R
, an opiton is to loop over the list
as well as the names
of the list
with Map
, extract the substr
ing from the names (could be done outside the loop as well as the substr
is vectorized), then assign the subset of column names of the data.frame
elements by paste
ing the substr
ing 'year' with the corresponding column names, and return the data.frame
SECCIONES_year <- Map(function(x, nm)
{
year <- substr(nm, nchar(nm)-4, nchar(nm))
names(x)[4:ncol(x)] <- paste0(names(x)[4:ncol(x)], year)
x
},
SECCIONES_year, names(SECCIONES_year))
In the OP's code, it could be assignment error i.e. instead of colnames(SECCIONES_year[[i]][,4:end_column])
it would be colnames(SECCIONES_year[[i]])[,4:end_column]
i.e. as an example
lst1 <- list(data.frame(col1 = 1:5, col2 = 6:10),
data.frame(col3 = 3:5, col4 = 4:6))
names(lst1) <- c("a", "b")
Checking the output with both the methods
# OP's method
> for(nm in names(lst1)) colnames(lst1[[nm]][2]) <- "hello"
> lst1
$a
col1 col2
1 1 6
2 2 7
3 3 8
4 4 9
5 5 10
$b
col3 col4
1 3 4
2 4 5
3 5 6
# modified
> for(nm in names(lst1)) colnames(lst1[[nm]])[2] <- "hello"
> lst1
$a
col1 hello
1 1 6
2 2 7
3 3 8
4 4 9
5 5 10
$b
col3 hello
1 3 4
2 4 5
3 5 6
Upvotes: 3