I am wanting to create variables age10, age20, age30, etc. for a specified data set. The input for the function add_ages is a data frame named df, where the new variables are created based on their relation to the existing variable age.
df <- data.frame(age=sample(1:100,10,replace=T))
add_ages <- function(d){
for(i in seq(10,100,10)){
d[,paste0("age",i)] <<- ifelse(i>=d[,"age"] & d[,"age"]<i+10,1,0)
}
}
add_ages(d=df)
However, when I run the code above, I get the following error:
Error in d[, paste0("age", i)] <<- ifelse(i >= d[, "age"] & d[, "age"] < :
object 'd' not found
I'm not sure I understand why d cannot be found, when I am defining it to be df. Any thoughts?