Reputation: 1017
I have a list of data frames
# Create dummy data
df1<-data.frame( c(1,2,3),c(2,3,4))
df2<-data.frame(c(5,6,7),c(4,5,6))
# Create a list
l<-list(df1, df2)
I would like to assign names to columns. As l[[1]][,1]
gives me access to the first column, I thought I could assign 'names' as the first column name by:
l<-lapply(l, function(x)names(x[[1]][,1]<-"names"))
But this gives me an error
Error in x[[1]][, 1] <- "names" :
incorrect number of subscripts on matrix
Edit: Added some dput initial data
dput(lapply(head(results1, 2), head, 2))
list(structure(c(1.27679607834331, 1.05090175857491), .Dim = 2:1, .Dimnames = list(
c("..a15.pdf", "..a17.pdf"), "x")), structure(c(2.096687569578,
2.19826038300833), .Dim = 2:1, .Dimnames = list(c("..a15.pdf",
"..a17.pdf"), "x")))
after trying to assign the name
dput(lapply(head(results1, 2), head, 2))
list(structure(c(1.27679607834331, 1.05090175857491), .Dim = 2:1, .Dimnames = list(
c("..a15.pdf", "..a17.pdf"), "names")), structure(c(2.096687569578,
2.19826038300833), .Dim = 2:1, .Dimnames = list(c("..a15.pdf",
"..a17.pdf"), "names")))
Output:
results1[1]
[[1]]
names
..a15.pdf 1.27679608
..a17.pdf 1.05090176
..a18.pdf 1.51820192
..a21.pdf 2.30296037
..a2TTT.pdf 1.48568732
Upvotes: 0
Views: 370
Reputation: 389325
You can subset the names
of the dataframe:
l <- lapply(l, function(x) {names(x)[1] <-"names";x})
l
In tidyverse
-
library(dplyr)
library(purrr)
l <- map(l, ~.x %>% rename_with(~'names', 1))
From the updated data it seems you have list of matrices and the first column is actually rowname which you can convert to a column and name it.
lapply(results1, function(x) {
mat <- cbind.data.frame(names = rownames(x), x)
rownames(mat) <- NULL
mat
})
#[[1]]
# names x
#1 ..a15.pdf 1.28
#2 ..a17.pdf 1.05
#[[2]]
# names x
#1 ..a15.pdf 2.1
#2 ..a17.pdf 2.2
Upvotes: 2