My code is as follows,
`FARS = read.csv("C:\\Users\\rb138\\Desktop\\FARS.csv", header = T, sep = ",", na.strings=c(""," ","NA-code","NA"))
Preprocessing = process() {
FARS$X = NULL
library(caTools)
is.na(FARS) <- FARS == "NULL"
miss<-function(x)
{
return(sum(is.na(x)/length(x)*100))
}
apply(FARS,2,FUN = miss)
Mode <- function (x, na.rm) {
xtab <- table(x)
xmode <- names(which(xtab == max(xtab)))
if (length(xmode) > 1) xmode <- ">1 mode"
return(xmode)
}
for (var in 1:ncol(FARS)) {
if (class(FARS[,var])=="numeric") {
FARS[is.na(FARS[,var]),var] <- mean(FARS[,var], na.rm = TRUE)
} else if (class(FARS[,var]) %in% c("character", "factor")) {
FARS[is.na(FARS[,var]),var] <- Mode(FARS[,var], na.rm = TRUE)
}
}
set.seed(45)
split = sample.split(FARS$airbagDeploy, SplitRatio = 0.70)
Train1 = subset(FARS, split == TRUE)
Test1 = subset(FARS, split == FALSE)
}`
If is pass it outside the object it is not throwing any error. But when i am running it inside the function its throwing the following exception:
Error: unexpected '}' in " }"
Also when i trying to save the Object in a RDS file, code as follows :
saveRDS(Preprocessing, file = "preprocessing_script.rds")
its is throwing the following exception :
Error in saveRDS(Preprocessing, file = "preprocessing_script.rds") :
object 'Preprocessing' not found
Data set used for this is FARS.csv from the package "gamclass" in R. In case if anyone requires the dataset, kindly as in your comments.
Thank you in advance.
Try modifying your code like this with separate function:
FARS = read.csv("C:\\Users\\rb138\\Desktop\\FARS.csv", header = T, sep = ",", na.strings=c(""," ","NA-code","NA"))
Preprocessing = function(FARS) {
FARS$X = NULL
library(caTools)
is.na(FARS) <- FARS == "NULL"
miss<-function(x)
{
return(sum(is.na(x)/length(x)*100))
}
apply(FARS,2,FUN = miss)
Mode <- function (x, na.rm) {
xtab <- table(x)
xmode <- names(which(xtab == max(xtab)))
if (length(xmode) > 1) xmode <- ">1 mode"
return(xmode)
}
for (var in 1:ncol(FARS)) {
if (class(FARS[,var])=="numeric") {
FARS[is.na(FARS[,var]),var] <- mean(FARS[,var], na.rm = TRUE)
} else if (class(FARS[,var]) %in% c("character", "factor")) {
FARS[is.na(FARS[,var]),var] <- Mode(FARS[,var], na.rm = TRUE)
}
}
set.seed(45)
split = sample.split(FARS$airbagDeploy, SplitRatio = 0.70)
Train1 = subset(FARS, split == TRUE)
Test1 = subset(FARS, split == FALSE)
}
Preprocessing(FARS)
Let me know if it works!