fhaney
fhaney

Reputation: 89

R code for create matrix having smaller value

I'm just learn R and I got an assignment regarding create a matrix containing column having all values smaller than 6 using apply and all.

So here is the code for matrix output

A<-matrix(c(1, 5, 5, 0, 5, 6, 3, 0, 3), nrow = 3, ncol = 3, byrow = TRUE, 
         dimnames = list(c("Row-1", "Row-2", "Row-3"), 
                         c("Column 1", "Column 2", "Column 3")))

But, then how I'm going to call for values smaller in 6 Then function apply I used as follow

apply(A, 2, A<6)

Upvotes: 2

Views: 40

Answers (1)

markus
markus

Reputation: 26353

Here is one option without apply.

A[, colSums(A < 6) == nrow(A)]
#      Column 1 Column 2
#Row-1        1        5
#Row-2        0        5
#Row-3        3        0

explaination

The first step is to create a logical matrix that assigns TRUE to all values < 6

A < 6
#      Column 1 Column 2 Column 3
#Row-1     TRUE     TRUE     TRUE
#Row-2     TRUE     TRUE    FALSE
#Row-3     TRUE     TRUE     TRUE

We use this matrix and calculate the sum of each column (TRUE equals 1, FALSE equals 0). This returns a named vector.

colSums(A < 6)
#Column 1 Column 2 Column 3 
#       3        3        2

You are looking for columns where all values are smaller than 6, so we need to check if the sum in each column is equal to the number of rows of your matrix.

colSums(A < 6) == nrow(A)
#Column 1 Column 2 Column 3 
#    TRUE     TRUE    FALSE

This logical vector is then used to subset your columns.

A[, colSums(A < 6) == nrow(A)]

Upvotes: 1

Related Questions