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:
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
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)})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With