0

I have a list with data in scientific notation that uses commas instead of dots as decimal separator. I want to change all commas to dots. Someone great in here showed me how to do this for dataframes:

text <- "3,063E+01 1,775E-02 6,641E-07 3,747E-02"
read.table(text=text, dec = ",")

     V1      V2        V3      V4
1 30.63 0.01775 6.641e-07 0.03747

df <- read.table(text=text)
df <- sapply(df, gsub, pattern = ",", replacement= ".")
df <- sapply(df, as.numeric)

     V1        V2        V3        V4 
3.063e+01 1.775e-02 6.641e-07 3.747e-02 

I wanted to do the same to a list using lapply but it did not work out:

mferg_matrix[[1]]
          X2        X3        X4
84 1,606E-07 1,642E-07 1,731E-07
85 2,883E-07 2,789E-07 2,554E-07

mferg_matrix <- lapply(mferg_matrix,gsub, pattern = ",", replacement= ".")

mferg_matrix[[1]]
[1] "c(30. 52)" "c(33. 55)" "c(35. 51)"

mferg_matrix <- lapply(mferg_matrix,as.numeric)

Es gab 11 Warnungen (Anzeige mit warnings())
> mferg_matrix[[1]]
[1] NA NA NA

It did not work out using sapply either.

curbholes
  • 557
  • 2
  • 5
  • 11

1 Answers1

0

You may need to use

lapply(mferg_matrix, function(x) {
           x[] <- lapply(
                       lapply(x,gsub, pattern = ",", replacement= "."),
                                  as.numeric)
                                x})

data

mferg_matrix <- list(structure(list(X2 = c("1,606E-07", "2,883E-07"),
X3 = c("1,642E-07","2,789E-07"), X4 = c("1,731E-07", "2,554E-07")),
.Names = c("X2", "X3", "X4"), class = "data.frame", row.names = c("84", "85")), 
 structure(list(X2 = c("1,606E-07", "2,883E-07"), X3 = c("1,642E-07", 
 "2,789E-07"), X4 = c("1,731E-07", "2,554E-07")), .Names = c("X2", 
 "X3", "X4"), class = "data.frame", row.names = c("84", "85"
 )), structure(list(X2 = c("1,606E-07", "2,883E-07"), X3 = c("1,642E-07", 
 "2,789E-07"), X4 = c("1,731E-07", "2,554E-07")), .Names = c("X2", 
 "X3", "X4"), class = "data.frame", row.names = c("84", "85"
 )))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • It works!! Accordingly I changed the other line to: mferg_matrix <- lapply(mferg_matrix,function(x) lapply(x,as.numeric)) – curbholes Dec 10 '14 at 18:22
  • Thank you!! Is R more complicated than other languages? I constantly doubt my sanity when using R and you guys just solve these problems so easily. – curbholes Dec 10 '14 at 18:23
  • @curbholes I think any language will become easier once you spent some time with its syntax. – akrun Dec 10 '14 at 18:25