简体   繁体   中英

How to mutate a new col in dataframe using a specific function and conditions? Tidyverse/R

First of all, I couldn't find a question related with my issue, apologies if this question was already answered.

I have a dataframe with some columns and I want to calculate a new value using a specific ecuation. I guess I have to use mutate() from tidyverse, but I want to avoid rows/samples where there're one or more 0 values. I don't know how I can check if there's any 0 when I'm using mutate() . Also, I don't know how I can apply my specific formula to create the new column.

I leave here a code to create a dataframe as an example of my issue.

set.seed(123)
df <- data.frame(
  time = seq(now(), now()+hours(11),by='hours'),
  a = sample(0:100,12),
  b = sample(0:100,12),
  c = sample((0:20)/1000,12))

df[1:3,]$a <- 0
df[3:5,]$b <- 0
df[3:4,]$c <- 0

# function: M = a*b+(1-e^(-c/2))
# if any 0 in the row -> M = NA
# else: apply function

The function could be written as

a*b*(1-exp(-c/2))

The final df should have 4 colums per each hour (row) (a,b,c and the new calculated M), but when a | b | c == 0, M = NA a | b | c == 0, M = NA a | b | c == 0, M = NA .

I will be very grateful for every little help. Cheers!

EDIT: The real function is more complex that this example, so it will not be always true that if one term (a,b,c,...) is 0, the resulting M is 0. Sorry, I didn't realised this postulate is true for the simplified equation. But I want to avoid any 0 value because they are from monitoring physiological variables and I know if one value is 0 in a sample, then the sample is wrong, so NA.

If any of a , b or c is 0 it returns M as 0 which can be changed to NA .

library(dplyr)

df %>%
  mutate(M = a*b*(1-exp(-c/2)), 
         M = na_if(M, 0))

#                  time  a  b     c         M
#1  2021-10-18 19:41:56  0 90 0.013        NA
#2  2021-10-18 20:41:56  0 56 0.016        NA
#3  2021-10-18 21:41:56  0  0 0.000        NA
#4  2021-10-18 22:41:56 13  0 0.000        NA
#5  2021-10-18 23:41:56 66  0 0.011        NA
#6  2021-10-19 00:41:56 41 71 0.014 20.305847
#7  2021-10-19 01:41:56 49 25 0.009  5.500115
#8  2021-10-19 02:41:56 42  6 0.012  1.507473
#9  2021-10-19 03:41:56 97 41 0.017 33.661237
#10 2021-10-19 04:41:56 24 97 0.008  9.293401
#11 2021-10-19 05:41:56 89 82 0.019 69.002718
#12 2021-10-19 06:41:56 68 35 0.015 17.783230

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM