[R] create a function with "subset" statement
JSHuang
js.huang at protective.com
Fri Jan 30 03:34:41 CET 2015
Hi,
The following is implemented with function named subsetAll. It calls the
function subset1. The input to subset1 is the matrix A and a vector
indicating the beginning and ending values for columns 1 and 2. Input to
subsetAll is the matrix A and a matrix that is row bind from those vectors
constitute the conditions.
> subset1
function(A,v)
{
A[A[,1] %in% v[1]:v[2] & A[,2] %in% v[3]:v[4],]
}
> subsetAll
function(A,m)
{
v <- as.vector(m[1,])
result <- subset1(A,v)
if (dim(m)[1] > 1)
{
for (i in 2:dim(m)[1])
{
v <- as.vector(m[i,])
result <- rbind(result,subset1(A,v))
}
}
result
}
> A
a b c
[1,] 1 1 -0.04160857
[2,] 1 2 0.75486670
[3,] 1 3 -0.21022257
[4,] 1 4 -1.02594314
[5,] 1 5 -1.91864901
[6,] 2 1 0.19760459
[7,] 2 2 -1.30046908
[8,] 2 3 0.30554275
[9,] 2 4 -0.41861494
[10,] 2 5 0.22763712
[11,] 3 1 1.20244853
[12,] 3 2 1.15425304
[13,] 3 3 -2.13727010
[14,] 3 4 -0.27288205
[15,] 3 5 -1.08974847
[16,] 4 1 0.44501360
[17,] 4 2 -2.79163479
[18,] 4 3 -0.26713804
[19,] 4 4 1.31392292
[20,] 4 5 1.75383175
> (mB <- rbind(c(1,2,1,2),c(3,3,1,1),c(4,4,1,4)))
[,1] [,2] [,3] [,4]
[1,] 1 2 1 2
[2,] 3 3 1 1
[3,] 4 4 1 4
> (B <- subsetAll(A,mB))
a b c
[1,] 1 1 -0.04160857
[2,] 1 2 0.75486670
[3,] 2 1 0.19760459
[4,] 2 2 -1.30046908
[5,] 3 1 1.20244853
[6,] 4 1 0.44501360
[7,] 4 2 -2.79163479
[8,] 4 3 -0.26713804
[9,] 4 4 1.31392292
> (mC <- rbind(c(1,4,1,2)))
[,1] [,2] [,3] [,4]
[1,] 1 4 1 2
> (C <- subsetAll(A,mC))
a b c
[1,] 1 1 -0.04160857
[2,] 1 2 0.75486670
[3,] 2 1 0.19760459
[4,] 2 2 -1.30046908
[5,] 3 1 1.20244853
[6,] 3 2 1.15425304
[7,] 4 1 0.44501360
[8,] 4 2 -2.79163479
> (mD <- rbind(c(1,2,1,3),c(3,3,1,2)))
[,1] [,2] [,3] [,4]
[1,] 1 2 1 3
[2,] 3 3 1 2
> (D <- subsetAll(A,mD))
a b c
[1,] 1 1 -0.04160857
[2,] 1 2 0.75486670
[3,] 1 3 -0.21022257
[4,] 2 1 0.19760459
[5,] 2 2 -1.30046908
[6,] 2 3 0.30554275
[7,] 3 1 1.20244853
[8,] 3 2 1.15425304
>
--
View this message in context: http://r.789695.n4.nabble.com/create-a-function-with-subset-statement-tp4702423p4702497.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list