Question
Is there a function, or a way to get rowSums
to work on only one column?
Example Data
col1 <- c(1,2,3)
col2 <- c(1,2,3)
df <- data.frame(col1, col2)
I can use rowSums
to sum each value in a row for two or more defined columns:
colsToAdd <- c("col1", "col2")
rowSums(df[,colsToAdd])
[1] 2 4 6
However, this fails when only on column is passed
colsToAdd <- c("col1")
rowSums(df[,colsToAdd])
Error in rowSums(df[, colsToAdd]) :
'x' must be an array of at least two dimensions
which makes sense when looking at the rowSums()
function:
> rowSums
function (x, na.rm = FALSE, dims = 1L)
{
if (is.data.frame(x))
x <- as.matrix(x)
if (!is.array(x) || length(dn <- dim(x)) < 2L)
## This line 'stops' the function if only one column is passed
Additional information
The columns will be selected by a user in a Shiny app and stored in a variable. This variable is then passed to rowSums
. The user can select one or more columns.
I could construct an ifelse
statement to check the length of the variable, but was wondering if there is a better/more elegant/single line solution that I'm not seeing?
You could try
rowSums(df[,colsToAdd, drop=FALSE])
According to ?'['
, by default,
x[i, j, ... , drop = TRUE]
Based on the documentation
drop: For matrices and arrays. If ‘TRUE’ the result is coerced to the lowest possible dimension
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