-1

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 !

Sotos
  • 51,121
  • 6
  • 32
  • 66
Ali Hadjihoseini
  • 941
  • 1
  • 11
  • 31
  • 1
    `P[] = lapply(P, function(x) as.numeric(as.character(x)))`. But you might want to clean up your non-numeric levels first... – Gregor Thomas Sep 29 '17 at 14:23
  • it seems your table has text lines in the columns, hence values such as [Hz] in column vH. You shouldn't convert your column to numeric but clean the table before creating the data.frame. – xraynaud Sep 29 '17 at 14:24
  • @Gregor Great ! Thanks ! It works very well :) without any cleaning – Ali Hadjihoseini Sep 29 '17 at 14:25

1 Answers1

1

Here's a dplyr solution that uses mutate_all

library(dplyr)
P %>% 
   mutate_all(as.character) %>% 
   mutate_all(as.numeric)
CPak
  • 13,260
  • 3
  • 30
  • 48