从R中的许多列中减去数据框中的列 [英] Subtract a column in a dataframe from many columns in R

查看:96
本文介绍了从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)

If you need to subtract the columns 3:ncol(df) from the second column

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

这篇关于从R中的许多列中减去数据框中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆