How to convert certain columns only to numeric?

前端 未结 4 1441
误落风尘
误落风尘 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])
    }
    

提交回复
热议问题