Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract a column in a dataframe from many columns in R

Tags:

dataframe

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]
}
like image 825
TPM Avatar asked Mar 04 '15 15:03

TPM


People also ask

How do I subtract one column from a different Dataframe?

We can create a function specifically for subtracting the columns, by taking column data as arguments and then using the apply method to apply it to all the data points throughout the column.

How do I subtract one column from another in R?

To minus one column from another in an R matrix, we first need to read the matrix as a data frame using as. data. frame then find minus the columns using minus sign and accessing the column of the data frame.

How do I remove multiple columns from a Dataframe in R?

We can delete multiple columns in the R dataframe by assigning null values through the list() function.


2 Answers

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

df[3:ncol(df)] <- df[3:ncol(df)]-df[,2]
like image 191
akrun Avatar answered Sep 17 '22 19:09

akrun


Another solution using dplyr::mutate_at() function

# 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)

like image 35
Tung Avatar answered Sep 17 '22 19:09

Tung