How do I add the values from many variables?
If I just had two variables (columns) I could simply go:
summation.variable <- variable1 + variable2
or if it was all in a dataframe:
transform(dataframe, summation.col = column1 + column2)
How do I do it if I have about 10 variables and I do not want to type each one as in col1+col2+col3+col4. To make matters worse my columns have quite long names and at times the exact columns that I use can change. I have a character vector with all the relevant column names in it but cannot think how to use it.
The following is useless since it adds every value in every column in every row and gives a single value for the whole lot.
sum(metrics)
The Syntax for Using Group By in SQLAny of the aggregate functions can be used on one or more than one of the columns being retrieved.
We can use data frames to allow summary functions to return multiple columns.
To Format multiple columns you need to go transform/ then highlight set of columns you wnat to change the data format(Percent, Whole number, etc.) then right click and choose Change type. Unfortunately there is no chose from here to select a decimal part but this is something eazy to do from Home tab.
You want to use rowSums (see the indexing with a character vector.)
tmp <- data.frame(a=1:2,b=3:4,d=5:6)
rowSums(tmp[,c("a","d")])
or, more generally, apply:
apply(tmp[,c("a","d")], 1, sum)
There are many ways to do this kind of operation (ie. apply a function across a row or column), but as Eduardo points out, apply is the most basic:
tmp <- data.frame(a=1:2,b=3:4,d=5:6)
apply(tmp, 1, prod)
This is a very flexible function. For instance, you can do both operations at once with this call:
apply(tmp, MARGIN=1, function(x) c(sum(x), prod(x)))
Performing the same analysis across columns is also simple (the MARGIN parameter describes whether you use rows or columns):
apply(tmp, MARGIN=2, function(x) c(sum(x), prod(x)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With