vendredi 5 mars 2021

apply function depending on columns value

I would like first to mean columns of a given dataframe, if the elements to be meaned satisfy a given condition (Age <18 years). To make things clear, what I want to do is to get a column wich is the mean age of children under 18 years old, otherwise report a 0. I tried the following codes :

df <- dataframe (A1 = c("58"; "51", "5", "88", "16", "24"), 
                  A2 = c ("75", "57", "44", "2", "81", "4"),
                  A3 = c ("1" ,"51", "65", "54", "88", "12"),
                  A4 = c ("24" ,"8", "81", "32", "5", "86"),
                  D1 = c("1", "0", "0", "1", "0", "0"),
                  D2 = c ("0", "0", "0", "1", "1", "0"),
                  D3 = c ("1", "0", "1", "1", "0", "0"),
                  D4 = c ("1", "1", "1", "0", "0", "0"))

df$X_mean <- apply(df[, c ("A1", "A2", "A3", "A4")],
                                   1, function(x) mean (which(x<18)))

I tried also :

my.fun<-function(x,y){
  if(x<18){
    mean}
}

df$X_mean<-apply(df,MAR=1,FUN=my.fun,x=df[, c ("A1", "A2", "A3", "A4")] )

Or,

df[, c ("A1", "A2", "A3", "A4")] %>%  mutate_if(x<18, mean)

All of these lines didn't work.

Also, I would like to create 4 columns (Cond_Di), depending on both specific columns Ai and Di (i=1 to 4)

if Ai < 18 and Di == 1 so Cond_Di = 1 otherwise 0. And make it for all the Ai and respective Di. That's to say : A1 and D1 ==> Cond_D1 , A2 and D2 ==> Cond_D2 etc.

Thanks a lot in advance for your help

Aucun commentaire:

Enregistrer un commentaire