I have following dataframe.
act | tar |
---|---|
4 | 3 |
NA | NA |
-5 | -4 |
0 | 0 |
NA | 3 |
To subtract column tar
from column act
i used following code. But it gives me error.
df <- df %>%
mutate(diff = if_else(!is.na(act) & !is.na(tar), act - tar, as.integer(NA))
I checked the class of both columns, and they are integer
. Can anyone please help me?
CodePudding user response:
base R
option:
df <- data.frame(act = c(4, NA, -5, 0, NA),
tar = c(3, NA, -4, 0, 3))
df$diff <- (df$act - df$tar)
df
#> act tar diff
#> 1 4 3 1
#> 2 NA NA NA
#> 3 -5 -4 -1
#> 4 0 0 0
#> 5 NA 3 NA
Created on 2022-07-09 by the reprex package (v2.0.1)
If you want to take the NA
in account, you can write a function and apply
that on your columns like this:
df <- data.frame(act = c(4, NA, -5, 0, NA),
tar = c(3, NA, -4, 0, 3))
minus <- function(x) sum(x[1],na.rm=T) - sum(x[2],na.rm=T)
df$diff <- apply(df[,c('act','tar')],1, function(x) sum(x[1],na.rm=T) - sum(x[2],na.rm=T))
df
#> act tar diff
#> 1 4 3 1
#> 2 NA NA 0
#> 3 -5 -4 -1
#> 4 0 0 0
#> 5 NA 3 -3
Created on 2022-07-09 by the reprex package (v2.0.1)
CodePudding user response:
A possible solution:
library(dplyr)
df %>%
mutate(z = act - tar)
#> act tar z
#> 1 4 3 1
#> 2 NA NA NA
#> 3 -5 -4 -1
#> 4 0 0 0
#> 5 NA 3 NA
CodePudding user response:
Using coalesce
you can get get the Non-NA value
df |>
mutate(diff = ifelse(is.na(act - tar), coalesce(act, -tar), act - tar))
act tar diff
1 4 3 1
2 NA NA NA
3 -5 -4 -1
4 0 0 0
5 NA 3 -3
CodePudding user response:
Your code is almost right, only a little problem, the "true" and "false" conditions should be the same type, and you missied one ")"
df <- df %>% mutate(diff = if_else((!is.na(act) & !is.na(tar)), as.integer(act - tar), as.integer(NA)))
df
A data.frame: 5 × 3
act tar diff
<dbl> <dbl> <int>
4 3 1
NA NA NA
-5 -4 -1
0 0 0
NA 3 NA
you can also try this
df <- df %>% mutate(diff = act - tar)