Background
This is an attempt to improve a previous question. The idea is to create a function where I pass a dataframe and optionally a vector with variable names, the function then iterate over the variables in the dataframe, if they are numeric they are transformed. If the vector of names is also passed, only the ones in the list are iterated.
Tools used
In order to create an "optional" argument I used the missing() function. Source.
The syntax to iterate over the vector was inspired from this dicussion here.
Code & where I am stuck:
transformDivideThousand <- function(data_frame, listofvars){
if (missing(listofvars)) {
data_frame[, sapply(data_frame, is.numeric)] =
data_frame[, sapply(data_frame, is.numeric)]/1000
} else {
for (i in names(data_frame)) {
for (i in listofvars) {
data_frame[[i]]<-data_frame[[i]]/1000
}
}
}
return(data_frame)
}
The call would look like:
test <- transformDivideThousand(cases, c("col2", "col3", "col15"))
Question
- What I am getting wrong on that code? I managed to make the optional argument work, but there is something wrong in the code. When I test it the variables from the list are converted to zeros.
Cautionary suggestion
- If you are down-voting the question, at very least justify why!