Reputation: 43
I have a list of length "x" and I want to change a column name of all data.frames within this list using a vector of characters of same length of this list, as described below:
a <- data.frame(rep(1:10), letters[1:10])
b <- data.frame(rep(11:20), letters[11:20])
l <- list(a,b)
nm <- c("letters1:10","letters11:20")
I want something like:
colnames(l[[1]]); colnames(l[[2]])
that gives me
[1] "rep.1.10." "letters.1.10."
[1] "rep.11.20." "letters.11.20."
I tried lapply(l, function(x) colnames(x)[2]<-nm)
but it returns me a list with nm only and I wanted a list with the original data.frames with updated colnames.
Thank you.
Upvotes: 1
Views: 87
Reputation: 79188
Map( function(x,y){colnames(x)[2] <-y;x},l,nm)
[[1]]
rep.1.10. letters1:10
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
6 6 f
7 7 g
8 8 h
9 9 i
10 10 j
[[2]]
rep.11.20. letters11:20
1 11 k
2 12 l
3 13 m
4 14 n
5 15 o
6 16 p
7 17 q
8 18 r
9 19 s
10 20 t
Upvotes: 0
Reputation: 12074
Cludgy, but it seems to work (if I've understood the question).
lapply(as.list(1:2), function(x){colnames(l[[x]])[2] <- nm[x];l[[x]]})
Upvotes: 1