[R] reshape

David Winsemius dwinsemius at comcast.net
Tue Nov 13 19:03:10 CET 2012


On Nov 12, 2012, at 10:16 PM, arun wrote:

> Hi,
> You can try this:
> dat1<-read.table(text="
> Rad:0
> Rad1:2
> Rad3:3
> ",sep="",header=FALSE)
> 
> 
>  Variable<-do.call(rbind,lapply(strsplit(as.character(dat1[[1]]),split=":"),`[`,1))
> n11<-do.call(rbind,lapply(strsplit(as.character(dat1[[1]]),split=":"),function(x) as.numeric(x[2])))

That seems unnecessarily complicated:

 dat <- read.table(text="Rad:0
 Rad1:2
 Rad3:3", sep=":")

 names(dat) <- c('Variable',    'n11')
 dat$n2 <- 2400- dat$n1

 dat
#---------#
  Variable n11   n2
1      Rad   0 2400
2     Rad1   2 2398
3     Rad3   3 2397

>  n12<-2400-n11
>  dat2<-data.frame(Variable,n11,n12)
>  dat2
> #  Variable n11  n12
> #1      Rad   0 2400
> #2     Rad1   2 2398
> #3     Rad3   3 2397
>  str(dat2)
> #'data.frame':    3 obs. of  3 variables:
> # $ Variable: Factor w/ 3 levels "Rad","Rad1","Rad3": 1 2 3
> # $ n11     : num  0 2 3
> # $ n12     : num  2400 2398 2397
> 
> #or if you want it as a matrix:
>  newmat<-do.call(rbind,strsplit(as.character(dat1[[1]]),split=":"))
>  n12<-2400-as.numeric(newmat[,2])
>  newmat2<-cbind(newmat,n12)
> colnames(newmat2)[1:2]<-c("Variable","n11")
> A.K.
> 
> 
> ----- Original Message -----
> From: farnoosh sheikhi <farnoosh_81 at yahoo.com>
> To: "r-help at R-project.org" <r-help at r-project.org>
> Cc: 
> Sent: Monday, November 12, 2012 5:52 PM
> Subject: [R] reshape
> 
> Hi,
> 
> I have a R output that looks as follow:
> Rad:0
> Rad1:2
> Rad3:3
> 
> I want to make a new matrix that looks like : sample size is 2400
> Variable    n11  n12
> Rad            0     2400-0=2400
> Rad1          2       2400-2
> Rad3  3      2400-3
>  
> Thanks a lot for your time and help:)
> Best,Farnoosh Sheikhi


Alameda, CA, USA




More information about the R-help mailing list