Convert data.frame columns from factors to characters

前端 未结 18 1563
时光取名叫无心
时光取名叫无心 2020-11-22 04:43

I have a data frame. Let\'s call him bob:

> head(bob)
                 phenotype                         exclusion
GSM399350 3- 4- 8- 25- 44+         


        
18条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 05:05

    This works transforming all to character and then the numeric to numeric:

    makenumcols<-function(df){
      df<-as.data.frame(df)
      df[] <- lapply(df, as.character)
      cond <- apply(df, 2, function(x) {
        x <- x[!is.na(x)]
        all(suppressWarnings(!is.na(as.numeric(x))))
      })
      numeric_cols <- names(df)[cond]
      df[,numeric_cols] <- sapply(df[,numeric_cols], as.numeric)
      return(df)
    }
    

    Adapted from: Get column types of excel sheet automatically

提交回复
热议问题