How to convert all column data type to numeric and character dynamically?

前端 未结 5 1269
礼貌的吻别
礼貌的吻别 2020-12-12 00:34

I convert my columns data type manually:

data[,\'particles\'] <- as.numeric(as.character(data[,\'particles\']))

This not ideal as the da

5条回答
  •  不知归路
    2020-12-12 01:01

    If you don't know which columns need to be converted beforehand, you can extract that info from your dataframe as follows:

    vec <- sapply(dat, is.factor)
    

    which gives:

    > vec
    particles  humidity timestamp      date 
         TRUE      TRUE     FALSE     FALSE 
    

    You can then use this vector to do the conversion on the subset with lapply:

    # notation option one:
    dat[, vec] <- lapply(dat[, vec], function(x) as.numeric(as.character(x)))
    # notation option two:
    dat[vec] <- lapply(dat[vec], function(x) as.numeric(as.character(x)))
    

    If you want to detect both factor and character columns, you can use:

    sapply(dat, function(x) is.factor(x)|is.character(x))
    

提交回复
热议问题