How to reshape data.frames in a list?
Question
I have a list like this
A <- data.frame(a = c(1, 2), b = c(3, 4))
B <- data.frame(c = c(1, 2), d = c(3, 4))
g <- list(var1 = A, var2 = B)
producing
> g
$var1
a b
1 1 3
2 2 4
$var2
c d
1 1 3
2 2 4
Now I want to transpose list elements like this
lapply(g, function(x) data.frame(t(x)))
but this produces a, b, c d, as rownames which is not what I want
> lapply(g, function(x) data.frame(t(x)))
$var1
X1 X2
a 1 2
b 3 4
$var2
X1 X2
c 1 2
d 3 4
I would like to generete a new column into these data.frames for a, b, c, and d. How to achieve this?
Solution
Point 1: if you are transposing data, it most likely means you should use arrays, not data.frames.
However, if this really is what you want to do, then simply cbind()
in the column names:
lapply(g, function(x) as.data.frame(cbind(colnames(x), t(x))))
$var1
V1 V2 V3
a a 1 2
b b 3 4
$var2
V1 V2 V3
c c 1 2
d d 3 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow