user3542209
user3542209

Reputation: 13

Finding sum in all rows with R

I have two vectors

x <- c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,4,4,4,4,4,5,5,6,6,6,6)
y <- c(1,1,2,3,4,2,2,4,4,4,3,3,1,4,2,3,1,4,4,4,2,2,2,3,3)

I found the number of values for each x (from 1 to 6) as

 t=table(x,y) 

and get the table with 6 rows and 4 columns. Then I calculate the sum in all rows as s=apply(t,1,sum) and get the error. Could anybody explain what I do wrong?

Upvotes: 0

Views: 71

Answers (1)

Anders Ellern Bilgrau
Anders Ellern Bilgrau

Reputation: 10263

What is the error? I don't get one with apply(t, 1, sum). Try instead

rowSums(t)
##1 2 3 4 5 6 
##5 5 4 5 2 4 

Or, you could simply use table(x), which gives you exactly the same output.

Upvotes: 2

Related Questions