错误:意外'}' in"}"

时间:2017-11-13 11:28:07

标签: r function exception save coding-style

我的代码如下,

`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)

  }`

如果将它传递到对象之外,它不会抛出任何错误。但是当我在函数内部运行它时会抛出以下异常:

Error: unexpected '}' in " }"

此外,当我尝试将对象保存在RDS文件中时,代码如下:

saveRDS(Preprocessing, file = "preprocessing_script.rds")

它抛出以下异常:

Error in saveRDS(Preprocessing, file = "preprocessing_script.rds") : object 'Preprocessing' not found

用于此的数据集是来自包&#34; gamclass&#34;的FARS.csv。在R. 如果有人需要数据集,请在评论中使用。

提前谢谢。

1 个答案:

答案 0 :(得分:1)

尝试使用单独的函数修改您的代码:

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)

让我知道它是否有效!