So for the dataset birthwt I want the percentage of low weight babies that are born from mothers that smoke and were under 20 years when given birth. In other words, I want how many <2600 of bwt (weight) are for age <20 and smoke == 1.
I run the next three chunks of code that actually gives you the correct answer:
# new df with the conditions
new_df <- subset(birthwt, age<20 & smoke==1)
#for loop to calculate the low weight
low_weight <- 0
for (i in 1:length(new_df$bwt)){
if(bwt[i] < 2600){
low_weight <- low_weight + 1
}
}
#low weight for the original dataset
low_weight_tot <- 0
attach(birthwt)
for (i in 1:length(birthwt$bwt)){
if(bwt[i] < 2600){
low_weight_tot <- low_weight_tot + 1
}
}
print(low_weight/low_weight_tot)*100
But I find it very tedious, is there any other simpler way of doing this with loops?
Thanks!