R - 如何用 rowsum 减去
R - how to subtract with rowsum
我的数据框看起来像这样。
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))`
我们可以对数据进行子集化以删除第一列 (.[-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
如果有更多的列并且想要select最后两列
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))
我的数据框看起来像这样。
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))`
我们可以对数据进行子集化以删除第一列 (.[-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
如果有更多的列并且想要select最后两列
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))