How to replace semicolon by dot in a dataframe in R Studio

Asked

Viewed 2,399 times

1

I am importing a CSV file where the data comes separated by commas, but I need to export them in the R pattern, which is the ".".

I have tried using the function as.Numeric, but the values disappear from the dataframe, and the function str_replace_all returns the error " argument is not an Atomic vector; coercing"

Dataframe with the data

1   252  2,0056
2   504  2,0881
3   756  2,4613
4   1260 2,8715
5   2520 3,3215
6   3024 3,4256
7   252  5,2604
8   504  5,7646
9   756  6,2504
  • Can you please, edit the question with the departure of dput(dados) or, if the base is too large, dput(head(dados, 20))? Note: dados is the name of the database, for example a data.frame. The link does not give us access to the data.

  • Hello, include the data, thank you for the suggestion.

2 answers

4


One way to replace decimal commas with dots is with as.numeric/sub.
Since the question dataframe is not very clear, I’m not sure if the first column is even a column or if it is the row.names, I will first determine in which columns there are commas. These columns will have a valueTRUE in the vector cols.

cols <- sapply(dados, function(x) any(grepl(",", x)))
dados[cols] <- lapply(dados[cols], function(x) as.numeric(sub(",", ".", x)))

Another way, as for me better, is to avoid the problem by reading the data with the argument dec = "," that many R functions of reading data have.

dados2 <- read.table(text = "
1   252  2,0056
2   504  2,0881
3   756  2,4613
4   1260 2,8715
5   2520 3,3215
6   3024 3,4256
7   252  5,2604
8   504  5,7646
9   756  6,2504
", dec = ",")

This is enough for the decimas to be separated by points:

identical(dados, dados2)
#[1] TRUE

Dice.

dados <- read.table(text = "
1   252  2,0056
2   504  2,0881
3   756  2,4613
4   1260 2,8715
5   2520 3,3215
6   3024 3,4256
7   252  5,2604
8   504  5,7646
9   756  6,2504
")

1

You can use the function read.csv2() which reads the comma-separated number files or can use as.numeric(sub(",", ".", Input, fixed = TRUE))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.