[R] select from matrix

Joshua Wiley jwiley.psych at gmail.com
Mon Aug 8 08:11:38 CEST 2011


Hi,


## Better way to make your matrix
A <- rbind(c(16,10,2,4,8,7),
c(16,10,12,14,8,7),
c(16,10,13,15,19,17),
c(16,9,13,15,9,7))


## Create logical matrices for conditions 1 & 2
B1 <- rowSums(A[, 2:4] < 10) > 0
B2 <- rowSums(A[, 5:6] < 10) > 0

## initialize X at the "catch all"
X <- rep(3L, nrow(A))

## overwrite values of X that meet condition 2
X[B2] <- 2L
## overwrite values of X that meet condition 1
X[B1] <- 1L

## Now turn these steps into a little function
## for benchmarking

make.ind <- function(A) {
  B1 <- rowSums(A[, 2:4] < 10) > 0
  B2 <- rowSums(A[, 5:6] < 10) > 0

  X <- rep(3L, nrow(A))
  X[B2] <- 2L
  X[B1] <- 1L
  return(X)
}

## replicate A to have 4 million rows
Abig <- do.call("rbind", rep(list(A), 10^6))

system.time(Xbig <- make.ind(Abig))

## On my system it takes less than 1 second
#   user  system elapsed
#   0.72    0.00    0.72

Hope this helps,

Josh

On Sun, Aug 7, 2011 at 10:50 PM, gallon li <gallon.li at gmail.com> wrote:
> Suppose I have a matrix like
>
> A=matrix(0,4,6)
> A[1,]=c(16,10,2,4,8,7)
> A[2,]=c(16,10,12,14,8,7)
> A[3,]=c(16,10,13,15,19,17)
> A[4,]=c(16,9,13,15,9,7)
>
>> A
>     [,1] [,2] [,3] [,4] [,5] [,6]
> [1,]   16   10    2    4    8    7
> [2,]   16   10   12   14    8    7
> [3,]   16   10   13   15    19    17
> [4,]   16    9   13   15    9    7
> I want to creat an indicator variable X which takes three values:
>
> X=1 if any of A[,2] to A[,4] is less than 10; for example, A[1,] and A[4,]
> is this group;
> X=2 if not the above but any of A[,5] to A[,6] is less than 10; for example,
> A[2,] is this group;
> X=3 if none of the above; for example, A[3,] belongs here.
>
> I wonder how to implement this fast in R?
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list