简体   繁体   English

通过 R 中的组 id 将 dataframe 转换为矩阵格式

[英]Transform a dataframe to matrix format by group id in R

I'm trying to convert a data.frame object into matrix format by some group id using the dlply function, but the resulting object clearly is not of matrix format.我正在尝试使用dlply function 通过某些组 id 将data.frame object 转换为matrix格式,但生成的 object 显然不是matrix格式。 Could anyone point out what's going on here?谁能指出这里发生了什么?

 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"

Wrong argument name, try this:错误的参数名称,试试这个:

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

In base R, you can use by :在基础 R 中,您可以by

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

Or split + lapply :split + lapply

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

A matrix can hold data of only one type in it.一个矩阵只能保存一种类型的数据。 Since you have characters as well as numbers in your data all the data is transformed to character.由于您的数据中有字符和数字,因此所有数据都转换为字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM