Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

How to smartly list the columns of a matrix into data frames while preserving the column names?

$
0
0

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")))

Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>