Home > OS >  ignore NA in basic calculations (no option for na.rm)
ignore NA in basic calculations (no option for na.rm)

Time:11-11

Im going to pursue a lot of basic calculations in R, ( -), and I see the coding suggestions out here are pretty complicated considering that I need to do this so many times.

Is there an easy way to come around NA values, basically treating them as 0s (like using nr.rm()) without actually converting them to 0s, when there are no option for na.rm.

Im going to pursue the calculations within every row. eg.

A = c(1,2,3,4)
hei <- as.data.frame(A)
hei$B = c(1,2,NA,4)

  A  B
1 1  1
2 2  2
3 3 NA
4 4  4

For instance

C <- hei$A hei$B

I want to become

  A  B  C
1 1  1  2
2 2  2  4
3 3 NA  3
4 4  4  8

CodePudding user response:

If you want to threat it as 0, and not actually change the value, you could make some sort of backup dataframe where the calculations are done (threating NA as zero) and then add the results to the original datafame.

A = c(1,2,3,4)
hei <- as.data.frame(A)
hei$B = c(1,2,NA,4)

dfBACKUP <- hei
dfBACKUP[is.na(dfBACKUP)] <- 0
dfBACKUP$C <- dfBACKUP$A dfBACKUP$B

hei$C <- dfBACKUP$C

hei

> hei
  A  B C
1 1  1 2
2 2  2 4
3 3 NA 3
4 4  4 8

CodePudding user response:

Using coalesce from dplyr

library(dplyr)
coalesce(hei$B, 0)
[1] 1 2 0 4

hei$c =  hei$A   coalesce(hei$B, 0)

  A  B c
1 1  1 2
2 2  2 4
3 3 NA 3
4 4  4 8

We an also use replace_na from tidyr

library(tidyr)
replace_na(hei$B, 0)
[1] 1 2 0 4
  •  Tags:  
  • r
  • Related