-1

I have a table of values 1, 2, 3, 4 randomly distributed across 35 rows and 15 columns. How can use the sum() function to just add the "4"s across the entire table, and also on a separate operation add all "4"s from a specific column.

Thanks,

This is the matrix:

m1imported <-matrix(sample(x = 1:4, size = 35*15, replace = TRUE), nrow = 35, ncol = 15)

us<c("CALIFORNIA","FLORIDA","ARIZONA","MICHIGAN","WASHINGTON","GEORGIA","TEXAS","OHIO","ALABAMA","COLORADO","NEW JERSEY","VIRGINIA","MONTANA","OREGON","NEW YORK")

colnames(m1imported) = us

num<-c(1:35)
rownames (m1imported) = num
pascal
  • 1,036
  • 5
  • 15
Noob in R
  • 21
  • 5
  • 1
    Could you provide more detail? Probably what you are looking is aggregate. – badalovi Jan 27 '21 at 06:04
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jan 27 '21 at 06:04

2 Answers2

3

To count 4's across entire matrix :

sum(m1imported == 4)

To count 4's across each column.

colSums(m1imported == 4)

To sum 4's across entire matrix :

sum(m1imported==4)*4

To sum 4's across each column.

colSums(m1imported==4)*4

vector of females:

females <- c(m1imported[1:20,])

vector of males:

males <- c(m1imported[-1:-(nrow(m1imported)-15),])
pascal
  • 1,036
  • 5
  • 15
  • Just double checked and they are asking for the number of 4's but regardless your answer is very useful for future purposes. – Noob in R Jan 27 '21 at 06:35
2

To count 4's across entire matrix :

sum(m1imported == 4)
#[1] 124

To count 4's across each column.

colSums(m1imported == 4)

#CALIFORNIA    FLORIDA    ARIZONA   MICHIGAN WASHINGTON    GEORGIA 
#        10         10          6          5         12          9 

#     TEXAS       OHIO    ALABAMA   COLORADO NEW JERSEY   VIRGINIA 
#         8         10          8          9          8         13 

#   MONTANA     OREGON   NEW YORK 
#         3          5          8 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • That was perfect thank you, and too easy. We just started this "basic" course and the instructor only showed us how to use == to return a TRUE or FALSE output when comparing 2 variables. And I am science major lol – Noob in R Jan 27 '21 at 06:33