[R] reshaping

Ista Zahn istazahn at gmail.com
Fri Mar 2 21:50:02 CET 2012


Hi,

I *think* this is what you want...

On Fri, Mar 2, 2012 at 12:29 PM, robgriffin247
<robgriffin247 at hotmail.com> wrote:
> Hello,
> I have a large data set which I am trying to get in to a long/narrow format.
> I have given an example below of how I want my data to look before and
> after... any ideas for an easy way to do this?
>
> *###Start With this...
> *set.seed(1)
> a=rnorm(10)
> b=rnorm(10)
> c=rnorm(10)
> d=rnorm(10)
> e=rnorm(10)
> f=rnorm(10)
> g=rnorm(10)
> h=rnorm(10)
> G=c(1,2,3,4,5,6,7,8,9,10)
> test=matrix(c(G,a,b,c,d,e,f,g,h),ncol=9)
> colnames(test)=c("G","a","b","c","d","e","f","g","h")
> *test*
>

library(reshape2)
test.m <- melt(as.data.frame(test), id.vars="G")

> ### WHERE...
>  # a-d = male. e-h > sex = female

test.m$sex <- ifelse(as.character(test.m$variable) %in% letters[1:4],
"male", "female")

>  # a,c,e,g > replicate = 1

test.m$replicate <- ifelse(as.character(test.m$variable) %in% c("a",
"c", "e", "g"), 1, 2)

>  # a+b > experimental line = L1, c+d =L2....

test.m$line <- paste(test.m$variable, test.m$G, sep = "")

HTH,
Ista

>
> *### Which Becomes This...
> *z2=as.numeric(c(seq(1:10),seq(1:10),seq(1:10),seq(1:10)))
> sex=c("m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m",
>
> "m","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f")
> rep=c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2)
> line=c("A1","A2","A3","A4","A5","A6","A7","A8","A9","A10","A1","A2","A3","A4","A5","A6","A7","A8","A9","A10","A1","A2","A3","A4","A5"
> ,"A6"   ,"A7"   ,"A8"   ,"A9"   ,"A10"  ,"A1"   ,"A2"   ,"A3"   ,"A4"   ,"A5"   ,"A6"   ,"A7"
> ,"A8"   ,"A9"   ,"A10")
> r=as.numeric(c(rnorm(10),rnorm(10),rnorm(10),rnorm(10)))
> test2=matrix(c(z2,sex,rep,line,r),ncol=5)
> colnames(test2)=c("G","Sex","Rep","Line","Res")
> *test2*
>
> --
> View this message in context: http://r.789695.n4.nabble.com/reshaping-tp4439182p4439182.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.



More information about the R-help mailing list