Reputation: 35
I (as a beginner in R) am trying to pass a list of dataframes as an input of a function to change some variables from char to dates. When I run the script it works. If I then try it in a function I don't get any error but the type of the variable is still a character. Below you can find the function. Thank you in advance for your suggestions.
data <- list(complaints,credit,customers,delivery,subscriptions,formula)
building <- function(x){
for (i in 1:6){
vars <- which(names(x[[i]]) %in% c("StartDate","EndDate","PaymentDate","RenewalDate","ProcessingDate","ComplaintDate","DOB"))
x[[i]][,vars] <- sapply(vars,function(vars) as.Date(x[[i]][,vars],format=f),simplify=FALSE)
}
complaints <- x[[1]]
credit <- x[[2]]
customers <- x[[3]]
delivery <- x[[4]]
subscriptions <- x[[5]]
formula <- x[[6]]
}
building(data)
Upvotes: 2
Views: 210
Reputation: 12411
You are trying to modify objects in your function that were defined outside of the function. This is called side effect in computer science: http://en.wikipedia.org/wiki/Side_effect_%28computer_science%29
You cannot do that in R.
Instead, you can do, for example that :
data <- list(complaints,credit,customers,delivery,subscriptions,formula)
building <- function(x){
for (i in 1:6){
vars <- which(names(x[[i]]) %in% c("StartDate","EndDate","PaymentDate","RenewalDate","ProcessingDate","ComplaintDate","DOB"))
x[[i]][,vars] <- sapply(vars,function(vars) as.Date(x[[i]][,vars],format=f),simplify=FALSE)
}
return(x)
}
output <- building(data)
complaints <- output [[1]]
credit <- output [[2]]
customers <- output [[3]]
delivery <- output [[4]]
subscriptions <- output [[5]]
formula <- output [[6]]
Upvotes: 1