简体   繁体   English

从 R 中的许多列中减去数据框中的一列

[英]Subtract a column in a dataframe from many columns in R

I have a dataframe.我有一个数据框。 I'd like to subtract the 2nd column from all other columns.我想从所有其他列中减去第二列。 I can do it in a loop, but I'd like to do it in one call.我可以循环完成,但我想在一次调用中完成。 Here's my working loop code:这是我的工作循环代码:

df <- data.frame(x = 100:101, y = 2:3,z=3:4,a = -1:0,b=4:5)

for( i in 3:length(df) ) {
    df[i] <- df[i] - df[2]
}

如果您需要从第二列中减去列3:ncol(df)

df[3:ncol(df)] <- df[3:ncol(df)]-df[,2]

Another solution using dplyr::mutate_at() function使用dplyr::mutate_at()函数的另一种解决方案

# install.packages("dplyr", dependencies = TRUE)
library(dplyr)

df <- data.frame(x = 100:101, y = 2:3, z = 3:4, a = -1:0, b = 4:5)
df %>%
  mutate_at(vars(-matches("y"), -matches("x")), list(dif = ~ . - y))
#>     x y z  a b z_dif a_dif b_dif
#> 1 100 2 3 -1 4     1    -3     2
#> 2 101 3 4  0 5     1    -3     2

Created on 2019-11-05 by the reprex package (v0.3.0)reprex 包(v0.3.0) 于 2019 年 11 月 5 日创建

This would also work - returns the 9 columns that you subtracted the second one from.这也可以 - 返回您从中减去第二列的 9 列。

 df = data.frame(matrix(rnorm(100,0,1),nrow = 10))
 df[,-2] - df[,2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM