Function for converting dataframe column type

后端 未结 1 1083
别那么骄傲
别那么骄傲 2020-12-29 17:44

R often understands data frame columns in a \"wrong\" format or you just have to change the column class from factor to character in order to modify it. I have been changing

相关标签:
1条回答
  • df <- data.frame(x = 1:10,
                     y = rep(1:2, 5),
                     k = rnorm(10, 5,2),
                     z = rep(c(2010, 2012, 2011, 2010, 1999), 2),
                     j = c(rep(c("a", "b", "c"), 3), "d"))
    
    convert.magic <- function(obj, type){
      FUN1 <- switch(type,
                     character = as.character,
                     numeric = as.numeric,
                     factor = as.factor)
      out <- lapply(obj, FUN1)
      as.data.frame(out)
    }
    
    str(df)
    str(convert.magic(df, "character"))
    str(convert.magic(df, "factor"))
    df[, c("x", "y")] <- convert.magic(df[, c("x", "y")], "factor")
    
    0 讨论(0)
提交回复
热议问题