hi all, Assume I have data like data<-rbind(c(1,2),c(1,3),c(2,1),c(3,2),c(3,4)) I want to get some matrix like 1,2,3 2,NA,NA 3,2,4 I'm using by mat<-matrix(NA,3,3) by(data,data[,1],mat[data[,1],]<-c(data[,2])) but it doesn't work. Any ideas? thanks, cowboy
how to use by function
3 messages · cowboy, arun, Rui Barradas
Hi, Not familiar with by function. But you can get the result : mat[,1]<-(rle(data[,1]))$values mat[1,]<-(rle(data[,1]))$values mat[3,2:3]<-(rle(data[,2])$values)[4:5]
mat
???? [,1] [,2] [,3] [1,]??? 1??? 2??? 3 [2,]??? 2?? NA?? NA [3,]??? 3??? 2??? 4 A.K. ----- Original Message ----- From: cowboy <dgecon at gmail.com> To: r-help at r-project.org Cc: Sent: Monday, June 18, 2012 11:32 PM Subject: [R] how to use by function hi all, Assume I have data like data<-rbind(c(1,2),c(1,3),c(2,1),c(3,2),c(3,4)) I want to get some matrix like 1,2,3 2,NA,NA 3,2,4 I'm using by mat<-matrix(NA,3,3) by(data,data[,1],mat[data[,1],]<-c(data[,2])) but it doesn't work. Any ideas? thanks, cowboy ______________________________________________ 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.
Hello,
Your code is not working because you are not understanding what's
written in the help page for 'by'.
'by' breaks its first argument, a data.frame, (could be matrix) into
sets of rows using 'index' to do the breaking. Each set of rows is the
argument for FUN, a function that already exists or an unnamed function
to be defined.
In this example, inspired by your "code", the unnamed function has
argument 'x'. That 'x' becomes each set taken from 'dat'. Take a look:
dat <- rbind(c(1,2),c(1,3),c(2,1),c(3,2),c(3,4))
mat <- matrix(NA, 3, 3)
by(dat, dat[, 1], FUN=function(x){ mat[x[, 1], ] <- x[, 2]; mat })
This is not what you want. How to do what you want is:
wanted <- read.table(text="
1,2,3
2,NA,NA
3,2,4
", sep=",")
(wanted <- as.matrix(wanted))
dimnames(wanted) <- NULL
index.mat <- which(!is.na(wanted), arr.ind=TRUE)
values <- wanted[index.mat]
how.to <- matrix(nrow=3, ncol=3)
how.to[index.mat] <- values
all.equal(wanted, how.to)
Or maybe you are just trying to understand 'by', in which case run the
examples in its help page.
Hope this helps,
Rui Barradas
Em 19-06-2012 04:32, cowboy escreveu:
hi all, Assume I have data like data<-rbind(c(1,2),c(1,3),c(2,1),c(3,2),c(3,4)) I want to get some matrix like 1,2,3 2,NA,NA 3,2,4 I'm using by mat<-matrix(NA,3,3) by(data,data[,1],mat[data[,1],]<-c(data[,2])) but it doesn't work. Any ideas? thanks, cowboy
______________________________________________ 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.