Create a function for rounding rows

Hey there,

I just want to build a function for rounding columns, because I need to do it a lot.
But somehow I get an error...

round.columns <- function(data, columnname, x){
  data$columnname <- round(data$columnname, digits = x)

Does someone may notice my mistake?

Thank you and cheers,

Here are three versions of such a function. It is important to remember that a function returns a value and that value has to be assigned to something if you want to preserve it. Modifying a data frame inside of a function, as you did, only changes the data frame in the environment of the function. The data frame that was passed into the function is not affected.
One problem with your function is that data$columnname refers to a column named "columnname" within the data frame named data. The fact that there is a variable named columnname inside of the function is irrelevant.You can see this by making a data frame named DF with a column named Number. DF$Number returns that column. If you make a variable named x and give it the value "Number", DF$x will not return the Number column. However, DF[[ x]] will return the Number column.

The first function below returns the entire data frame and the name of the column is passed as a string. The second function returns only the modified column and I assign that value to the column in the original data frame. The column name is again passed in quotes. The third function returns the entire data frame and the column name can be passed unquoted because I use the mutate function from dplyr and the {{ operator from rlang. I am sure there are many other possible ways to write the function but I do not think any of them save all that much effort compared to using round() directly.

DF <- data.frame(GPMT=c(rnorm(n = 10)))

round.columns <- function(data, columnname, x){
  data[[columnname]] <- round(data[[columnname]], digits = x)
DF <- round.columns(DF,"GPMT",3)

DF <- data.frame(GPMT=c(rnorm(n = 10)))
round.columns2 <- function(data, columnname, x){
  round(data[[columnname]], digits = x)
DF$GPMT <- round.columns2(DF,"GPMT",3)

DF <- data.frame(GPMT=c(rnorm(n = 10)))
round.columns3 <- function(data, columnname, x){
  mutate(data,{{columnname}} := round({{columnname}}, digits=x))
DF <- round.columns3(DF,GPMT,2)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.