简体   繁体   中英

How to use R function properly

I have a dataframe named data and columns comfort , condition and few others. I do one and the same manipulations with 5 columns and decided to write the following function:

replacing_na_999<-function(df, variable){
  #variable<-as.name(variable)
  levels <- levels(df$variable)
  levels[length(levels) + 1] <- "999"
  df$variable <- factor(df$variable, levels = levels)
  df$variable[is.na(df$variable)] <- "999"
}

When I try:

replacing_na_999(data, comfort)

it returns an error:

 Error in `$<-.data.frame`(`*tmp*`, variable, value = integer(0)) : 
  replacement has 0 rows, data has 44070 

Can someone help me please with syntaxis?

this works on my computer

m<-structure(list(district = structure(c(6L, 21L, 20L, 19L, 5L, 8L), 
                                           .Label = c("I", "II", "III", "IV", "IX", "V", "VI", "VII", "VIII", "X", "XI", "XII", "XIII", "XIV", "XIX", "XV", "XVI", "XVII", "XVIII", "XX", "XXI", "XXII", "XXIII"),
                                           class = "factor"), 
                      ln_price = c(5.52146091786225, 4.9416424226093, 4.74493212836325, 5.01063529409626, 4.55387689160054, 5.07517381523383)), 
                 row.names = c(NA, 6L), class = "data.frame")
    m[4,1]<-NA
    m

    m<-sapply(m,function(x) {
      if(is.factor(x))
        factor(x,levels=c(levels(x),999))
      else x
    }
    )

    m[is.na(m)]<-999
    m

perhaps something on the line of:

replacing_na_999<-function(df, variable){
  idx <- which(variable == names(df))
  #variable<-as.name(variable)
  levels <- levels(df[idx])
  levels[length(levels) + 1] <- "999"
  df[idx] <- factor(df[idx], levels = levels)
  df[idx][is.na(df[idx])] <- "999"
  return(df)
}

will avoid to pass the name as argument to your function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM