【问题标题】:Transform a dataframe to matrix format by group id in R通过 R 中的组 id 将数据帧转换为矩阵格式
【发布时间】:2021-07-21 15:06:35
【问题描述】:

我正在尝试使用dlply 函数将data.frame 对象转换为matrix 格式,但结果对象显然不是matrix 格式。 谁能指出这里发生了什么?

library(plyr)

#load the data
export <- readRDS(url("https://www.dropbox.com/s/7nn4kcdbsiteplj/export.rds?dl=1"))

export_mat <- dlply(export,.(reporter_iso), fun = as.matrix)

str(export_mat)

List of 161
 $ afg:'data.frame':    161 obs. of  6 variables:
  ..$ reporter_iso: chr [1:161] "afg" "afg" "afg" "afg" ...
  ..$ partner_iso : chr [1:161] "afg" "ago" "alb" "are" ...
  ..$ cong_pct    : num [1:161] 0 0 0 0.0915 0 ...
  ..$ cag_pct     : num [1:161] 0 0 0 0.0297 0 ...
  ..$ ig_pct      : num [1:161] 0 0 0 0.049 0 ...
  ..$ rm_pct      : num [1:161] 0 0 0 0.83 0 ...
  ..- attr(*, "vars")= chr "reporter_iso"
 $ ago:'data.frame':    161 obs. of  6 variables:
  ..$ reporter_iso: chr [1:161] "ago" "ago" "ago" "ago" ...
  ..$ partner_iso : chr [1:161] "afg" "ago" "alb" "are" ...
  ..$ cong_pct    : num [1:161] 0 0 0 0.203 0 ...
  ..$ cag_pct     : num [1:161] 0 0 0 0.698 0 ...
  ..$ ig_pct      : num [1:161] 0 0 0 0.0148 0 ...
  ..$ rm_pct      : num [1:161] 0 0 0 0.0842 1 ...
  ..- attr(*, "vars")= chr "reporter_iso"

【问题讨论】:

    标签: r dataframe matrix plyr


    【解决方案1】:

    参数名称错误,试试这个:

    export_mat <- dlply(export,.(reporter_iso), .fun = as.matrix)
    

    【讨论】:

    • 我通过 R 4.0.2 和 plyr v1.8.6 进行了测试
    • 非常感谢!奇怪的是,dlply 函数将单元格内的数值变成了“字符”。
    【解决方案2】:

    在基础 R 中,您可以使用 by

    export_mat <- by(export, export$reporter_iso, as.matrix)
    

    split + lapply

    export_mat <- lapply(split(export, export$reporter_iso), as.matrix)
    

    一个矩阵只能保存一种类型的数据。由于您的数据中包含字符和数字,因此所有数据都将转换为字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多