I got this data.frame
Data = data.frame( Time = seq(1,5),
v1 = c(0.1, 0.2, 0.4, 0.7, 0.9),
v2 = c(0.1, 0.12, 0.41, 0.72, 0.91),
v3 = c(0.03, 0.13, 0.62, 0.50, 0.90))
but i need to subtrate a certain value in all columns
subtrate = data.frame(v1 = 0.1, v2 = 0.3, v3 = 0.5)
To get this result:
result =
v1 v2 v3
1 0.0 -0.20 -0.47
2 0.1 -0.18 -0.37
3 0.3 0.11 0.12
4 0.6 0.42 0.00
5 0.8 0.61 0.40
CodePudding user response:
With purrr
you can try:
map2_df(Data[-1], subtrate, `-`)
Output
v1 v2 v3
<dbl> <dbl> <dbl>
1 0 -0.2 -0.47
2 0.1 -0.18 -0.37
3 0.3 0.11 0.12
4 0.6 0.42 0
5 0.8 0.61 0.4
CodePudding user response:
We could do:
library(tidyverse)
Data %>%
pivot_longer(-Time) %>%
left_join(subtrate %>% pivot_longer(everything(), values_to = 'minus'), by = 'name') %>%
mutate(value = value - minus) %>%
select(-minus) %>%
pivot_wider()
Which gives:
# A tibble: 5 x 4
Time v1 v2 v3
<int> <dbl> <dbl> <dbl>
1 1 0 -0.20 -0.47
2 2 0.1 -0.18 -0.37
3 3 0.3 0.110 0.12
4 4 0.6 0.42 0
5 5 0.8 0.61 0.4
CodePudding user response:
With base R, we can use mapply
:
Data[-1]<-mapply(\(x,y) x - y, Data[-1], subtrate)
Data
Time v1 v2 v3
1 1 0.0 -0.20 -0.47
2 2 0.1 -0.18 -0.37
3 3 0.3 0.11 0.12
4 4 0.6 0.42 0.00
5 5 0.8 0.61 0.40