Subtract a column in a dataframe from many columns in R

后端 未结 3 1168
闹比i
闹比i 2020-11-29 12:17

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 cod

相关标签:
3条回答
  • 2020-11-29 12:44

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

    df[3:ncol(df)] <- df[3:ncol(df)]-df[,2]
    
    0 讨论(0)
  • 2020-11-29 12:54

    This would also work - returns the 9 columns that you subtracted the second one from.

     df = data.frame(matrix(rnorm(100,0,1),nrow = 10))
     df[,-2] - df[,2]
    
    0 讨论(0)
  • 2020-11-29 13:05

    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)

    0 讨论(0)
提交回复
热议问题