How to sum the values in each column

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

How to sum the values in each column

John G. Read
Hi All,

I have a simple query that I am really struggling to solve. Let me first describe my data to you.

I have a dataset called "trial" which has an ID column and 100 other variables (these 100 variables are all binary coded: 0 and 1).

E.g. trial:

ID      Var1 Var2 Var3 ... Var100
ID1    0      1      0            0
ID2    0      1      1            1
ID_n  0      1      0            0

In addition, I have an object called "variables" which simply contains some of the column names from "trial" (but never the ID column) as a character vector. E.g. "variables" : Var3 Var27 Var91

I want to write some code to sum the values down each column in "trial" that are in my "variables" list. How can I go about doing this? The reason why I can't do it manually (i.e. sum(trial$var3), etc.) is because this "variables" object is sometimes recycled and replaced with a new "variables" list with different column names from "trial". I hope that makes sense.

I look forward to your reply. Thanks in advance,