Woj
Woj

Reputation: 469

R data frame: convert all data frame elements from characters to numerics while keeping decimals

I have a data frame that looks like this.

   V1      V2     V3      V4       V5   V6
1:  1 0.007d0 0.73d0 4.165d0 1438.8d0 6050

The d notation is alike to scientific notation.

THe problem here is that when I read the numbers with these ds into R, R treat them as characters instead of numerics. Is there a way to read the table in and change all the elements to numeric, all the while preserving the decimals?

Upvotes: 1

Views: 61

Answers (3)

Jason Mathews
Jason Mathews

Reputation: 805

You can use str_remove to remove pattern and convert to numeric using mutate

library("dplyr")
library("stringr")


df %>% mutate(across(everything(), ~ as.numeric(str_remove(.,"d"))))

Upvotes: 0

Anoushiravan R
Anoushiravan R

Reputation: 21908

Here is a tidyverse solution:

library(dplyr)
library(stringr)

DF %>%
  mutate(across(everything(), ~ as.numeric(str_replace(., "d(?=\\d+)", "e"))))

  V1    V2   V3    V4     V5   V6
1  1 0.007 0.73 4.165 1438.8 6050

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101044

Do you mean something like below?

df[] <- lapply(
  df,
  function(x) {
    eval(str2lang(gsub("d","e",x)))
  }
)

and you will see

> df
  V1    V2   V3    V4     V5   V6
1  1 0.007 0.73 4.165 1438.8 6050

> str(df)
'data.frame':   1 obs. of  6 variables:
 $ V1: num 1
 $ V2: num 0.007
 $ V3: num 0.73
 $ V4: num 4.16
 $ V5: num 1439
 $ V6: num 6050

data

> dput(df)
structure(list(V1 = 1L, V2 = "0.007d0", V3 = "0.73d0", V4 = "4.165d0",
    V5 = "1438.8d0", V6 = 6050L), class = "data.frame", row.names = "1")

Upvotes: 3

Related Questions