如何在 R 中重新格式化表格?
问题描述:
我像这样加载了一个表格:
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
并且我需要将其格式化为如下所示的格式,其中 V1 表示行,V2 表示列,以及 V3 中的值:
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
请注意,pat1 与 pat2 与 pat3 的观察数不同,缺失值必须用 0 填充.
Please, note that pat1 vs. pat2 vs. pat3 have different numbers of observations and that missing values must be filled with 0.
答
Using dcast
from reshape2
:
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
数据在哪里:
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)