I'm new to programming and don't quite understand the logic behind functions in R just yet. I want to create a function which is able to handle four variables, with conditions in three of these deciding the result in the fourth variable; and that goes through all cases in the data set. For the sake of simplicity, lets say my data frame has four variables (var1 to var4) with 100 cases each:
f1 <- function(w, x, y, z) {
for (n in seq_along(w)) {
if (!is.na(w[n]) & !is.na(x[n]) & !is.na(y[n])){
z[n]<-0
}else if (!is.na(w[n]) & !is.na(x[n]) & is.na(y[n])){
z[n]<-1
}else if (!is.na(w[n]) & is.na(x[n]) & is.na(y[n])){
z[n]<-2
}else if (!is.na(w[n]) & is.na(x[n]) & !is.na(y[n])){
z[n]<-3
} } }
f1(df$var1, df$var2, df$var3, df$var4)
Why doesn't the function work?
Aucun commentaire:
Enregistrer un commentaire