【问题标题】:R - how to subtract with rowsumR - 如何用rowsum减去
【发布时间】:2018-12-28 02:28:27
【问题描述】:

我的数据框看起来像这样。

df <- read.table(text="
                 column1  column2   column3
    1            3        2         1
    1            3        2         1 
", header=TRUE)

我需要从第一列中减去最后两列。为了计算那些列,我会使用rowSums(summary[,1:3]),但我不知道如何减去这些列。请注意,我不能像这样编写代码,因为我不知道列名。

`result <- df %>% 
mutate(result = rowSums(column1, - column2, - column3))` 

【问题讨论】:

    标签: r rowsum


    【解决方案1】:

    我们可以对数据进行子集化以删除第一列 (.[-1]),得到 rowSums 并从 'column1' 中减去

    library(tidyverse)
    df %>%
        mutate(result = column1 - rowSums(.[-1]))
    #   column1 column2 column3 result
    #1       3       2       1      0
    #2       3       2       1      0
    

    如果有更多列并且想要选择最后两列

    df %>%
        mutate(result = column1 - rowSums(.[tail(names(.), 2)]))
    

    如果我们只有操作所涉及的列的索引

    df %>% 
        mutate(result = .[[1]] - rowSums(.[c(2, 3)]))
    

    数据

    df <- structure(list(column1 = c(3L, 3L), column2 = c(2L, 2L), column3 = c(1L, 
     1L)), class = "data.frame", row.names = c(NA, -2L))
    

    【讨论】:

    • 但是如果我只知道 column1 的索引但现在知道它的名称怎么办?
    • @Sklenicka 在这种情况下使用它作为向量,即df %&gt;% mutate(result = column1 - rowSums(.[c(2, 3)]))
    • 你是说你只知道所有列的索引。那就试试df %&gt;% mutate(result = .[[1]] - rowSums(.[c(2, 3)]))
    猜你喜欢
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多