# Passing matrix columns as arguments to a function

Usually, when how turns out to be difficult, it's because of losing sight of what.

Every `R` problem can be thought of with advantage as the interaction of three objects— an existing object, x , a desired object,y , and a function, f, that will return a value of y given x as an argument. In other words, school algebra— f(x) = y. Any of the objects can be composites.

In the code given in the OP, x is a matrix dim 3 8, `m` and y is a logical vector of length 8. The objective is to populate y according to the equality tests for m[1,][1] == m[2,][2] and m[1,][1] == m[3,][1], which could be generalized to every other row if desired. For this use case, `colSums` is convenient, but not necessary. An alternative is presented below. Understand the application of the arguments to the subset operator, `[``m[,]` subsets everything, `m[1,]` returns all columns for row 1, `m[,1] returns all rows for column 1, `m[2:3,3:4]`and`m[c(1,3),c(5,7)]` specified rows and columns.

See the FAQ: How to do a minimal reproducible example `reprex` for beginners to better frame questions.

``````# final element changed from 0 to 1 to conform to desired output

dat <- c(0,0,0,0,1,1,1,1,0,0,1,1,0,0,1,1,0,1,0,1,0,1,1,1)
m <- matrix(dat, nrow = 3, ncol = 8)

a_function <- function(x) colSums(x) == 0 | colSums(x) == 3

a_function(m)
#> [1]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE

another_function <- function(x,y) pi * m[y,] > 0

another_function(m,1:3)
#>       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7] [,8]
#> [1,] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE TRUE
#> [2,] FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE TRUE
#> [3,] FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE TRUE

a_third_function <- function(x,y,z) x[y+1,] == x[y+z,]

a_third_function(m,1,2)
#> [1]  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE  TRUE
``````