How can I reformat a table in R?

浪子不回头ぞ 提交于 2021-01-28 02:30:50

问题


I loaded a table like this:

    V1  V2   V3
  pat1   1    2
  pat1   3    1
  pat1   4    2
  pat2   3    3
  pat3   1    4
  pat3   2    3

and I need to format it into something like the following, with V1 indicating the row, V2 indicating the column, and the values in V3:

         1    2    3    4
 pat1    2    0    1    2
 pat2    0    0    3    0
 pat3    4    3    0    0

Please, note that pat1 vs. pat2 vs. pat3 have different numbers of observations and that missing values must be filled with 0.


回答1:


Using dcast from reshape2 :

library(reshape2)
dcast(dat,V1~V2,fill=0)

    V1 1 2 3 4
1 pat1 2 0 1 2
2 pat2 0 0 3 0
3 pat3 4 3 0 0

Where dat is :

dat <- read.table(text='V1  V2   V3
  pat1   1    2
  pat1   3    1
  pat1   4    2
  pat2   3    3
  pat3   1    4
  pat3   2    3',header=TRUE)



回答2:


The base R alternative is to use xtabs:

xtabs(V3 ~ V1 + V2, mydf)
#       V2
# V1     1 2 3 4
#   pat1 2 0 1 2
#   pat2 0 0 3 0
#   pat3 4 3 0 0

or reshape:

reshape(mydf, direction = "wide", idvar = "V1", timevar = "V2")
#     V1 V3.1 V3.3 V3.4 V3.2
# 1 pat1    2    1    2   NA
# 4 pat2   NA    3   NA   NA
# 5 pat3    4   NA   NA    3


来源:https://stackoverflow.com/questions/28890541/how-can-i-reformat-a-table-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!