Say we have a matrix M
.
# n1 n2 n3 n4
# m1 1 4 7 10
# m2 2 5 8 11
# m3 3 6 9 12
In order to list the columns as "data.frames"
we can do:
apply(M, 2, data.frame)
However, the listed data frames have weird and identical column names, e.g.:
# $n1
# newX...i.
# m1 1
# m2 2
# m3 3
Same thing with lapply
:
lapply(data.frame(M), data.frame)
# $n1
# X..i..
# 1 1
# 2 2
# 3 3
The only way I have found to get my expected output so far is doing:
lapply(1:ncol(M), function(x) setNames(data.frame(M[,x]), colnames(M)[x]))
# [[1]]
# n1 ## <-- expected col names!
# m1 1
# m2 2
# m3 3
This turns out to be unexpectedly cumbersome. Have I maybe missed a simpler base function?
Data
M <- structure(1:12, .Dim = 3:4, .Dimnames = list(c("m1", "m2", "m3"
), c("n1", "n2", "n3", "n4")))