Quantcast

Sum part of row and add this as a new column vector

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Sum part of row and add this as a new column vector

Peterso
This post has NOT been accepted by the mailing list yet.
County 1990 1991 1992 1993
Alachua 1 1 1 1
Baker 0 0 0 0
Bay 0 0 1 0
Bradford 0 0 0 0


I would like to add up all the scores for each year and add it as a new Total column. I tried to use matrix functions, they they assume all data is numeric. I need to add only from column 2 to n. It should look like the table below.

Johnny

County 1990 1991 1992 1993   Total
Alachua 1 1 1 1              4
Baker 0 0 0 0              0
Bay 0 0 1 0              1
Bradford 0 0 0 0              0
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Sum part of row and add this as a new column vector

Rui Barradas
Hello,

Try

df1 <- read.table(text="
County 1990 1991 1992 1993
Alachua 1 1 1 1
Baker 0 0 0 0
Bay 0 0 1 0
Bradford 0 0 0 0
", header=TRUE)

df1$Total <- rowSums(df1[ , -1]) # Not column 1
df1$Total <- rowSums(df1[ , 2:5])# Explicit column numbers

Hope this helps,
Rui Barradas
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Sum part of row and add this as a new column vector

Peterso
This post has NOT been accepted by the mailing list yet.
Everything is simple when you know what you're doing.

Thanks, it worked exactly as I wanted it.
 Johnny
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Sum part of row and add this as a new column vector

Indrajit Sen Gupta
This post has NOT been accepted by the mailing list yet.
In reply to this post by Peterso
You can the "apply" function to compute like this:

dt <- read.table("peter.txt", header = TRUE)

total <- apply(X= dt[,2:5], MARGIN = 1, FUN = sum)

final <- cbind(dt, total)

Regards,
Indrajit
Loading...