【问题标题】:How to creating data frame from a matrix [duplicate]如何从矩阵创建数据框[重复]
【发布时间】:2018-02-11 15:51:47
【问题描述】:

我正在寻找一个 cvs 文件,其中包含一个矩阵,其中每个行/列组合都有一个特定的速率。见例子:

我想将信息作为数据框读取,其中每个值都与 $Year,$Age,$Rate 的行/列因子相关联。见例子:

谢谢!

CS

更新:感谢您的反馈,我已经编写了自己的函数并且似乎可以解决问题:

matrix2dataframe <- function(rowN,colN,Data) {
  NRowRep = max(rowN)-min(rowN)
  NColRep = max(colN)-min(colN)

  tmp_Name = rep(as.character(Data[rowN[1],colN[1]]),times=NRowRep*NColRep)
  tmp_Value =     as.numeric(as.matrix(Data[rowN[2]:max(rowN),colN[2]:max(colN)]))
  tmp_Age =     rep(as.character(as.matrix(Data[rowN[2]:max(rowN),1])),times=NColRep)
  tmp_DYear =     mapply(rep,x=as.character(as.matrix(Data[rowN[1],2:max(colN)])),times=NRowRep)
  tmp_DYear = as.character(tmp_DYear)
  #list(Cancer = tmp_Name,Rate = tmp_Value,Age = tmp_Age,DYear = tmp_DYear)
  data.frame(Cancer = tmp_Name,Rate = tmp_Value,Age = tmp_Age,DYear =     tmp_DYear)
}

【问题讨论】:

  • 请提供样本数据和/或数据图像。
  • 您可以为两个示例 data.frames 而不是两张图片提供dput 的输出。请参阅此处了解如何提出好问题stackoverflow.com/questions/5963269/…
  • 这与您的其他问题 stackoverflow.com/questions/46019182/… 并没有真正的不同。您是否看过任何涵盖此内容的介绍性指南 - 如果是的话,您能否展示您尝试过的代码以及您遇到的问题。谢谢
  • 感谢您的链接。我找不到任何默认函数,所以我最终自己写了

标签: r csv matrix dataframe


【解决方案1】:

只需使用reshape

 melt(df)

    age  variable value
1 15-99  one_year  76.3
2 15-44  one_year  92.9
3 15-99 five_year  60.9
4 15-44 five_year  82.8

【讨论】:

    【解决方案2】:

    看看这个:

    df <- data.frame(age = c("15-99", "15-44"), "one_year" = c(76.3, 92.9), "five_year" = c(60.9, 82.8))
    df
        age one_year five_year
    1 15-99     76.3      60.9
    2 15-44     92.9      82.8
    
    library(tidyr)
    gather(df, year, rate, -age)
        age      year  rate
    1 15-99  one_year  76.3
    2 15-44  one_year  92.9
    3 15-99 five_year  60.9
    4 15-44 five_year  82.8
    

    如果您确实有一个矩阵作为开始,您可以使用data.frame() 函数将其转换为数据框。看看?data.frame。如果年龄组是行名,请考虑使用df$age = row.names(df) 将行名转换为列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 2018-03-15
      • 2014-11-30
      • 1970-01-01
      相关资源
      最近更新 更多