Home > Enterprise >  Taking the difference of multiple cells by one cell
Taking the difference of multiple cells by one cell

Time:07-30

Currently I have a df for finding a difference in precipitation That looks like this

col1 col2 col3 col4 col5

1........2..........0.......4........3

5........4..........1.......3........4

2........2..........4.......0........0

And I am trying to figure out how to subtract all 4 col from col5 separately so i should have a df that is similar to the one below

col1 col2 col3 col4

-2.....-1......-3......1

1........0.......-3......-1

2.......2.........4.......0

I know this may be simple to many but I am completely new to dplyer and code in general. If anyone could help that would be amazing!

CodePudding user response:

If your data is in a dataframe you can directly subset it with indices and do the following substraction

# the dataframe
> df
  V1 V2 V3 V4 V5
1  1  2  0  4  3
2  5  4  1  3  4
3  2  2  4  0  0
df[,1:4] - df[,5]

produces

> df[,1:4] - df[,5]
  V1 V2 V3 V4
1 -2 -1 -3  1
2  1  0 -3 -1
3  2  2  4  0

I think this is most basic way to solve your problem. There will be a lot more ways achieve the same thing with different syntax.

CodePudding user response:

dplyr option using mutate with across like this:

df <- data.frame(col1 = c(1,5,2),
                 col2 = c(2,4,2),
                 col3 = c(0,1,4),
                 col4 = c(4,3,0),
                 col5 = c(3,4,0))

library(dplyr)
df %>% 
  mutate(across(col1:col4, ~.x - col5)) %>%
  select(-col5)
#>   col1 col2 col3 col4
#> 1   -2   -1   -3    1
#> 2    1    0   -3   -1
#> 3    2    2    4    0

Created on 2022-07-29 by the reprex package (v2.0.1)

  • Related