【问题标题】:Convert data from list like data.frame to matrix like data.frame?将数据从像data.frame这样的列表转换为像data.frame这样的矩阵?
【发布时间】:2017-10-21 09:42:32
【问题描述】:

我想将数据从列表形式转换为矩阵形式。

我的数据如下所示:

dataFrame.list

     compound    time    concentration
1    compA        1       0.5
2    compA        2       0.3
3    compB        2       0.7
4    compB        3       0.8
5    compA        3       0.5
6    compC        1       0.4
7    compC        3       0.1

我想以下列形式获得它:

     compound    time1     time2     time3
1    compA        0.5       0.3       0.5
2    compB        NA        0.7       0.8
3    compC        0.4       NA        0.1

我有几个问题:

dataframe.matrix

  1. 构造新的空数据框
  2. 使用变量名寻址正确的列。

这是我目前所拥有的:

# uniqe list of compounds
uniqueCompoundList <- unique(dataFrame.list$compound)


# unique vector of times
compoundTime <- as.character(sort(unique(dataFrame.list$time)))


# new matrix like dataframe (This doesn't work but kind of shows what I would like)
dataframe.matrix <- data.frame("compound", compoundTime)

for (singleCompound in uniqueCompoundList){

   # subset based on name
   singeCompoundData <- subset(dataFrame.list, compound == singleCompound)

   # put name in new matrix
   dataframe.matrix$compound <- compound

   for (time in singleCompound$time)){

     # put the value of concentration under the column equal to time
     dataframe.matrix$time <- singleCompound$concentration
   }

}

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    我们可以使用dcast

    library(reshape2)
    dcast(df1, compound ~paste0("time", time))
    #   compound time1 time2 time3
    #1    compA   0.5   0.3   0.5
    #2    compB    NA   0.7   0.8
    #3    compC   0.4    NA   0.1
    

    或与xtabs 来自base R

    xtabs(concentration~compound + time, df1)
    

    【讨论】:

      猜你喜欢
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 2021-12-23
      • 2019-09-09
      • 2015-01-06
      • 2019-09-11
      • 1970-01-01
      相关资源
      最近更新 更多