从R中的许多列中减去一个dataframe中的列

时间:2021-10-18 22:55:49

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:

我有一个dataframe。我想从所有其他列中减去第二列。我可以做一个循环,但我想做一次调用。下面是我的工作循环代码:

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]
}

2 个解决方案

#1


2  

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

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

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

#2


0  

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]

#1


2  

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

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

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

#2


0  

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]