Jim Underwood
2013-Feb-19 22:29 UTC
[R] Help reshaping a dataset with multiple tuples per row
I have a dataset which contains several multi-column measurement sets per row. Col 1 identifies patient: Col1 Col2 Col3 Col 4 Col 5 Col 6 Col7 ... Patient Treatment Outcome Advice Treatment Outcome Advice "P1" "T1" "O1" "A1" "T2" "O2" "A2" Please advise a reshape strategy to generate an output frame with a single measurement per row, e.g., Col1 Col2 Col3 Col4 Patient Treatment Outcome Advice "P1" "T1" "O1" "A1" "P1" "T2" "O2" "A2"
Hi,
Try this:
dat1<- read.table(text="
Patient? Treatment Outcome? Advice Treatment? Outcome? Advice
P1??????? T1????????????? O1????????? A1??????? T2??????????? O2????????? A2
",sep="",header=TRUE,stringsAsFactors=FALSE)
names(dat1)[-1]<-paste(gsub("\\..*","",names(dat1)[-1]),"_",rep(1:2,each=3),sep="")
?res<-reshape(dat1,direction="long",varying=2:7,sep="_")
row.names(res)<- 1:nrow(res)
?res<- res[,-c(2,6)]
?
?res
?# Patient Treatment Outcome Advice
#1????? P1??????? T1????? O1???? A1
#2????? P1??????? T2????? O2???? A2
A.K.
----- Original Message -----
From: Jim Underwood <droolinggeezer at gmail.com>
To: r-help at r-project.org
Cc:
Sent: Tuesday, February 19, 2013 5:29 PM
Subject: [R] Help reshaping a dataset with multiple tuples per row
I have a dataset which contains several multi-column measurement sets per row.
Col 1 identifies patient:
Col1? ? ? ? Col2? ? ? ? ? ? Col3? ? ? ? ? Col 4? ? Col 5? ? ? ? ? ? Col 6? ? ?
Col7? ...
Patient? Treatment? Outcome? Advice? Treatment? Outcome? Advice
"P1"? ? ? ? "T1"? ? ? ? ? ? ? "O1"? ? ? ? ?
"A1"? ? ? ? "T2"? ? ? ? ? ? "O2"? ? ? ? ?
"A2"
Please advise a reshape strategy to generate an output frame with a single
measurement per row, e.g.,
Col1? ? ? ? Col2? ? ? ? ? Col3? ? ? ? Col4
Patient? Treatment Outcome Advice
"P1"? ? ? ? "T1"? ? ? ? ? ? ? "O1"? ? ? ? ?
"A1"
"P1"? ? ? ? "T2"? ? ? ? ? ? ? "O2"? ? ? ? ?
"A2"
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.