Monday, August 26, 2019

r - Data frame to numeric?




I have a data.frame with the following structure :



str(P)

'data.frame': 24 obs. of 5 variables:
$ vH : Factor w/ 101 levels "[Hz]","[m/s]",..: 34 51 66 71 76 78 83 4 9 11 ...
$ P_el: Factor w/ 48 levels " ","[dB(A)]",..: 26 18 27 34 15 17 20 21 24 23 ...
$ CP : Factor w/ 92 levels "-"," ","[-]",..: 30 39 41 44 45 43 40 37 35 33 ...
$ CT : Factor w/ 68 levels " ","[-]","[kg/m³]",..: 4 4 4 4 4 4 4 4 4 4 ...
$ TSR : Factor w/ 87 levels "-"," "," -20 to 45",..: 35 32 76 75 75 74 72 69 67 66 ...

head(P)
vH P_el CP CT TSR
31 3 41 0.152229609724618 0 15.8

32 4 231 0.36183539476084 0 11.8
33 5 528 0.423450793411543 0 9.6
34 6 957 0.444157733251402 0 9.5
35 7 1524 0.445420179261082 0 9.5
36 8 2242 0.438979954033443 0 9.1


How could I get the numeric columns without doing a for loop :



n=ncol(P)

for(j in 1:n){P[,j]=as.numeric(as.character(P[,j]))}


I have tried data.matrix(P) but it does not work !


Answer



Here's a dplyr solution that uses mutate_all



library(dplyr)
P %>%
mutate_all(as.character) %>%

mutate_all(as.numeric)

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...