1

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

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))` 
4

1 回答 1

2

我们可以对数据进行子集化以删除第一列 ( .[-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))
于 2018-12-28T02:29:23.817 回答