1
votes

The numbers in this data.frame are rounded to 3 decimal places:

habitats_df <- data.frame(habitat = c("beach", "grassland", "freshwater"), v1 = c(0.000, 0.670, 0.032), v2 = c(0.005, 0.824, 0.012))

     habitat    v1    v2
1      beach 0.000 0.005
2  grassland 0.670 0.824
3 freshwater 0.032 0.012

I need them rounded to 2 decimal places. I tried to use plyr::l_ply like this:

library(plyr)
l_ply(habitats_df[,2:3], function(x) round(x, 2))

But it didn't work. How can I use plyr:: l_ply to round the numbers in habitats_df?

2

2 Answers

4
votes

You don't really need plyr for this, since a simply lapply combined with round does the trick. I provide a solution in base R as well as plyr

Try this in base R:

roundIfNumeric <- function(x, n=1)if(is.numeric(x)) round(x, n) else x

as.data.frame(
  lapply(habitats_df, roundIfNumeric, 2)
)

     habitat   v1   v2
1      beach 0.00 0.00
2  grassland 0.67 0.82
3 freshwater 0.03 0.01

And the same with plyr:

library(plyr)
quickdf(llply(habitats_df, roundIfNumeric, 2))

     habitat   v1   v2
1      beach 0.00 0.00
2  grassland 0.67 0.82
3 freshwater 0.03 0.01
1
votes
# plyr alternative
library(plyr)
data.frame(habitat = habitats_df$habitat,
           numcolwise(.fun = function(x) round(x, 2))(habitats_df))

#      habitat   v1   v2
# 1      beach 0.00 0.00
# 2  grassland 0.67 0.82
# 3 freshwater 0.03 0.01

# base alternative
data.frame(habitat = habitats_df$habitat,
           lapply(habitats_df[ , -1], function(x) round(x, 2)))