通过 R 中的组 ID 将数据帧转换为矩阵格式

Transform a dataframe to matrix format by group id in R

我正在尝试使用 dlply 函数通过某个组 ID 将 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"

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

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

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

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

split + lapply :

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

一个矩阵只能容纳一种类型的数据。由于您的数据中既有字符也有数字,因此所有数据都转换为字符。