【问题标题】:Round multiple vectors in dataframe with plyr使用 plyr 舍入数据框中的多个向量
【发布时间】:2014-01-24 08:41:47
【问题描述】:

此 data.frame 中的数字四舍五入到小数点后 3 位:

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_plyhabitats_df 中的数字进行四舍五入?

【问题讨论】:

    标签: r plyr


    【解决方案1】:

    您实际上并不需要 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
    

    【讨论】:

      【解决方案2】:
      # 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)))
      

      【讨论】:

        猜你喜欢
        • 2016-11-19
        • 1970-01-01
        • 2013-11-21
        • 1970-01-01
        • 2012-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-25
        相关资源
        最近更新 更多