Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to round factors throughout a dataframe using R?

I have a dataframe with a mix of characters and numbers in each column that are ultimately considered character columns like this:

df1 <- data.frame(
  Group = c('Type', 'State', 'Roads'),
  Value1 = c('A', 'Florida', 107.188887)
)

I want to round the number data points to the tenth digit, but this doesn’t seem possible given they are intermingled with other data types. Is there a way to do this rounding using R? The result would look like this:

df_desired <- data.frame(
  Group = c('Type', 'State', 'Roads'),
  Value1 = c('A', 'Florida', 107.2)
)

I’d prefer to avoid pivoting the df if possible.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Find the elements that are only numeric and do the rounding in base R itself

i1 <- grep("^[0-9.]+$", df1$Value1)
df1$Value1[i1] <- round(as.numeric(df1$Value1[i1]), 1)

-output

> df1
  Group  Value1
1  Type       A
2 State Florida
3 Roads   107.2

If it is an entire dataset, use lapply

df1[] <- lapply(df1, function(x) {
     i1 <- grep("^[0-9.]+$", x)
     x[i1] <- round(as.numeric(x[i1]), 1)
    x
})

-output

> df1
  Group  Value1
1  Type       A
2 State Florida
3 Roads   107.2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading