How to convert certain columns only to numeric?

前端 未结 4 1435
误落风尘
误落风尘 2020-12-11 18:25

How can I convert certain columns only in a data frame to numeric?

For instance, I have this data frame:

structure(list(airport = c(         


        
相关标签:
4条回答
  • 2020-12-11 18:55

    The all.is.numeric function from the Hmisc package does a good job determining whether a given column can be cast to numeric.

    Using this, you could do:

    numeric_cols <- sapply(weatherDF, Hmisc::all.is.numeric)
    
    if (sum(numeric_cols) > 1)  {
        weatherDF[,numeric_cols] <- data.matrix(weatherDF[,numeric_cols])
    } else {
        weatherDF[,numeric_cols] <- as.numeric(weatherDF[,numeric_cols])
    }
    
    0 讨论(0)
  • 2020-12-11 19:00
    num.cols <- c('ws','wd','humidity')
    weatherDF[num.cols] <- sapply(weatherDF[num.cols], as.numeric)
    
    0 讨论(0)
  • 2020-12-11 19:00

    Using dplyr:

    library(dplyr)
    df %>% 
      mutate_at(vars(ws, wd, humidity), as.numeric)
    
    # A tibble: 2 x 5
    airport xdate         ws    wd humidity
      <chr>   <chr>      <dbl> <dbl>    <dbl>
    1 EGLL    2016-07-28    6.  237.      68.
    2 EGLL    2016-07-31    5.  299.      55.
    
    0 讨论(0)
  • 2020-12-11 19:08

    1) All your columns is character columns <- sapply(weatherDF, is.character)

    airport    xdate       ws       wd humidity 
        TRUE     TRUE     TRUE     TRUE     TRUE
    

    2) Why not simply ?

    weatherDF[, 3:ncol(weatherDF)] <- lapply(3:ncol(weatherDF), function(x) as.numeric(weatherDF[[x]]))

    or

    columns <-c("ws", "wd", "humidity")
    weatherDF[, columns] <- lapply(columns, function(x) as.numeric(weatherDF[[x]]))
    

    If your dont know which columns is numeric you can try to find it using tryCatch like

    weatherDF[,1:ncol(weatherDF)]=lapply(1:ncol(weatherDF),function(x) {
      tryCatch({
        as.numeric(weatherDF[[x]])
        },warning = function(w) {
        weatherDF[[x]]}
            )} )
    
    0 讨论(0)
提交回复
热议问题