[R] how to use by function

Rui Barradas ruipbarradas at sapo.pt
Tue Jun 19 09:46:20 CEST 2012


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.
>



More information about the R-help mailing list