【问题标题】:How to transform a list of tables into a list of dataframes without changing the formats of the tables?如何在不更改表格格式的情况下将表格列表转换为数据框列表?
【发布时间】:2022-11-05 01:03:55
【问题描述】:

我有这个列表(我们只关心它是 2 个表的列表)

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)

当我申请lapply时如下

lapply(L,as.data.frame)

我有这个结果

[[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

我试图包含函数spread 来解决这个问题,但没有与我一起工作。将不胜感激

【问题讨论】:

    标签: r dataframe datatables lapply frequency


    【解决方案1】:

    table 对象可以转换为 matrixdata.frame,以便保持相同的结构

    L1 <- lapply(L, as.data.frame.matrix)
    

    -输出

    > 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
    

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      相关资源
      最近更新 更多