2014-01-24 25 views
1

在此data.frame的數字四捨五入至小數點後3位:回合多個向量與plyr

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 

我需要他們四捨五入至小數點後2位。我試圖使用這樣的plyr::l_ply

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

但它沒有奏效。我如何使用plyr:: l_ply來整理habitats_df中的數字?

回答

4

你真的不需要plyr這個,因爲一個簡單的lapplyround的伎倆結合。我提供在基礎R的溶液以及plyr

嘗試這種在基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 

並與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
# 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)))