Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying round function to every element in a dataframe

Tags:

loops

r

Suppose I have a dataframe in R like this

x = c(2, 3.432, 5)
y = c(4.5345, NA, "text")
z = c(8.13451, 3.12451, 6.12341)
A = data.frame(x, y, z)

How do I apply the round function to the appropriate elements of the dataframe? Essentially I want to:

  • Check if element is numeric
  • If not, make no changes
  • If numeric, round it to 3 decimal places

I have read in numerous places that loops are not a good idea in R. Trying lines like

A$y[is.numeric(A$y)] <- round(A$y, digits = 3)

does not work

like image 706
Shekar Avatar asked Jan 07 '17 05:01

Shekar


1 Answers

We can try with lapply

A[] <- lapply(A, function(x) if(is.numeric(x)) round(x, 3) else x)

If we need to change the format of numeric elements in those with character/factor class columns as well

A[] <- lapply(A, function(x) {
           x1 <- type.convert(as.character(x), as.is=TRUE)
    ifelse(grepl("^[0-9.]+$", x1), round(as.numeric(x1), 3), x1)})
like image 187
akrun Avatar answered Nov 14 '22 01:11

akrun