lundi 18 janvier 2021

if else statement loop over several conditions and multiple columns

I'm new to R and used to work with Matlab beforehand. Now I'm trying to calculate the chance that a specific condition occurs with an if -else loop. But as I discovered an if statement only uses the first row. My data consists among others over a column showing the age groups numbered 1 to 4, a column either if someone is male or female with a column Male 0 or 1 and a column Female 0 or 1.

So for every row I like to calculate the chance that it is male or female and belongs to that agegroup.

what I'v tried so far was so far only if a row was Male or Female.

Data$Chance <- with(Data,
                              ifelse(Female==1,sum(Female == 1)/nrow(Data),ifelse(Female==0,sum(Female==0)/nrow(Data))))

and the following (column 14 represents the Female column)

for(i in 1:nrow(Data)){
  if(Data[i,14]== 1){
    Data$Chance <- c(sum(Data$Female == 1)/length(Female))
  } else(Data[i,14] == 0) {
    Data$Chance<- c(sum(Data$Female == 0)/length(Female))
  }}

I know it should be really simple but I cant figure it out myself. I hope someone can explain how Ive to do this!?

Aucun commentaire:

Enregistrer un commentaire