Reputation: 911
I have this list (all we care that it is a list of 2 tables)
set.seed(222)
df = data.frame(x = trunc(runif(10,0,2)),
y = trunc(runif(10,4,6)),
z = trunc(runif(10,19,21)),
m = trunc(runif(10,28,30)))
df
t1 = table(df$x,df$y)
t2=table(df$z,df$m)
L = list(t1,t2)
when I apply lapply
as follows
lapply(L,as.data.frame)
I have this outcome
[[1]]
Var1 Var2 Freq
1 0 4 0
2 1 4 2
3 0 5 5
4 1 5 3
[[2]]
Var1 Var2 Freq
1 19 28 2
2 20 28 3
3 19 29 3
4 20 29 2
I tried to include the function spread
to fix this problem but did not work with me.
Upvotes: 1
Views: 44
Reputation: 887128
The table
object can be converted to matrix
and to a data.frame
so that it will keep the same structure
L1 <- lapply(L, as.data.frame.matrix)
-output
> str(L1)
List of 2
$ :'data.frame': 2 obs. of 2 variables:
..$ 4: int [1:2] 4 3
..$ 5: int [1:2] 2 1
$ :'data.frame': 2 obs. of 2 variables:
..$ 28: int [1:2] 3 1
..$ 29: int [1:2] 2 4
> L1
[[1]]
4 5
0 4 2
1 3 1
[[2]]
28 29
19 3 2
20 1 4
If we need proportions
lapply(L, \(x) 100 *as.data.frame.matrix(proportions(x)))
Upvotes: 3