Reputation: 11
I have a list of several strings, and I need to create a list of identical dataframes from it. The strings, for example, are a-d. The list should be
[1] xa
[2] xb
[3] xc
[4] xd
where each element is a dataframe. Each dataframe should have its columns named from another list (the column names are identical across dataframes)
strings <- c("a", "b", "c", "d")
DFList <- list()
for (i in 1:4){
DFList <- c(DFList,
assign(paste0("x",strings[i]),
data.frame(matrix(0,ncol=5,nrow=0))))
}
doesn't work. It returns 4 dataframes, and a list of 20 elements (4 * 5 columns).
After they're created, I need to then be able to add rows to certain ones of those dataframes later in the script, which I also can't figure out.
How can I go about this?
Upvotes: 0
Views: 138
Reputation: 32426
You can use replicate
or lapply
with setNames
setNames(replicate(4, data.frame(matrix(0,4,5)), simplify=FALSE), paste0("x", strings))
The default column names of the data.frames are "X1","X2",etc. So, if you have another list of names for the columns just wrap in another setNames
, like setNames(data.frame(...), otherNames)
.
The lapply
syntax is pretty similar,
setNames(lapply(1:4, function(i) data.frame(matrix(0,4,5))), paste0("x", strings))
Upvotes: 1