0

I'm just starting out in R and I'm trying to round all the numbers with no decimals in my data frame, preferably when I'm reading in a file.

I've looked up several ways to round decimals, but it is not clear to me where to place the code and what exactly to put in.

Could someone explain to me how to do this in the simplest way possible? I'm working through an R script.

lo_coder
  • 3
  • 1
  • Hi @lo_coder, can you [please make sure your question is more specific](https://stackoverflow.com/help/how-to-ask), [shows the code you've tried](https://stackoverflow.com/q/5963269/3277821), and how your current results differ from what you expect? A good place to start would be reading the documentation for the `round` function and [this related SO post](https://stackoverflow.com/q/3443687/3277821). – sboysel Oct 20 '19 at 05:23
  • You can `round`/`floor` after the fact, or on read in specify integer classes to the appropriate parameter, e.g. in `read.csv`, `colClasses`. – alistaire Oct 20 '19 at 05:26

2 Answers2

2

Where df is the name of the data.frame, and the 0 in the round function is number of decimals:

df <- data.frame(lapply(df, function(x){ if(is.numeric(x)){round(x, 0)}else{x}}))      

Data used:

df <- data.frame(x1 = c(84.2,105.2,79.2,140.2,108.2,79.2,112.2,118.2,114.2,92.2),
             x2 = c(138.3,110.3,84.3,45.3,128.3,99.3,100.3,124.3,121.3,115.3),
             x3 = as.character(c(138.3,110.3,84.3,45.3,128.3,99.3,100.3,124.3,121.3,115.3)),
             stringsAsFactors = FALSE)
hello_friend
  • 5,682
  • 1
  • 11
  • 15
  • Please accept my answer if it is correct so this thread can be closed ! – hello_friend Oct 20 '19 at 07:13
  • Could you explain what I did wrong here? lake_levels <- lake_lv_data(lapply(lake_levels, function(x){if(is.numeric(x)){round(x,0)}else{x}})) %>% clean_names() %>% rename( lake_lvl_abv_sea = lake_level_feet_above_sea_level) %>% purrr::modify_if(is.character, as.numeric) – lo_coder Oct 20 '19 at 17:35
  • data.frame is a function call so your code should read: data.frame(lapply(lake_lv_data, function(x){(if is.numeric(x)){round(x,0)}else{x}})) – hello_friend Oct 20 '19 at 20:58
0

Nevermind, found a simple function round_half_up() which solved the problem!

lo_coder
  • 3
  • 1