一列上的rowSums

tos*_*pig 7 r

是否有一个功能,或rowSums只能在一个列上工作的方法?

示例数据

col1 <- c(1,2,3)
col2 <- c(1,2,3)
df <- data.frame(col1, col2)
Run Code Online (Sandbox Code Playgroud)

我可以使用rowSums两行或更多定义列的行中的每个值相加:

colsToAdd <- c("col1", "col2")
rowSums(df[,colsToAdd])
[1] 2 4 6 
Run Code Online (Sandbox Code Playgroud)

但是,仅在传递列时失败

colsToAdd <- c("col1")
rowSums(df[,colsToAdd])
Error in rowSums(df[, colsToAdd]) : 
  'x' must be an array of at least two dimensions
Run Code Online (Sandbox Code Playgroud)

这看起来很有意义rowSums():

> 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
Run Code Online (Sandbox Code Playgroud)

附加信息

这些列将由用户在Shiny应用程序中选择并存储在变量中.然后将此变量传递给rowSums.用户可以选择一列或多列.

我可以构造一个ifelse语句来检查变量的长度,但是想知道是否有更好/更优雅/单行的解决方案,我没有看到?

akr*_*run 8

你可以试试

rowSums(df[,colsToAdd, drop=FALSE])
Run Code Online (Sandbox Code Playgroud)

根据?'[',默认情况下,

x[i, j, ... , drop = TRUE]
Run Code Online (Sandbox Code Playgroud)

根据文档

drop:对于矩阵和数组.如果为"TRUE",则结果将强制转换为可能的最低维度