如何舍入 R 列表中的值 - 仅舍入数值?

How to round values in R list - round only numeric values?

我的问题好像this一样简单,但是我不明白哪里出了问题。

我有以下数据:

myData <- structure(list(structure(0.964671123392506, .Names = "W"), 0.022361343060769242, 
                         structure(0.964695704055953, .Names = "W"), 0.022162269470046909, 
                         structure(0.958418109351607, .Names = "W"), 0.045107813263059401, 
                         structure(0.874545371360235, .Names = "W"), 1.59340622525965e-06), .Dim = c(2L, 
                                                                                                     4L), .Dimnames = list(c("Measure", "c-value"), c("col1", 
                                                                                                                                                      "col2", "col3", "col4")))

这是列表:

typeof(myData)
[1] "list"

我希望将所有元素四舍五入到选定的位数。我不能简单地应用 round 函数,所以我写了以下函数:

roundMe <- function(x, numbers=3) 
  {
  if ( is.numeric(x) ) {x <- as.character(sprintf("%3.2f", round(x, digits=numbers)))}
  #there's problem:
  x
}

并尝试应用它

apply(myData,1:2,roundMe)

给出:

        col1   col2   col3   col4  
Measure List,1 List,1 List,1 List,1
c-value List,1 List,1 List,1 List,1

当我将 roundMe(函数的最后一行)中的 "x" 更改为 as.character(x) 时,它 returns 不是四舍五入的数字。 怎么了?我应该使用另一个应用功能吗?我应该将列表转换为例如数据框吗?

你有一个列表。不要使用apply,它会强制转换为矩阵,而是使用lapply[<-结合使用,在保持原始结构的情况下替换myData的内容,

现在,我看不出有任何理由在您可以只使用 round 并保留数字字段时尝试强制转换为字符

myData[] <- lapply(myData,round,2)
myData
#         col1 col2 col3 col4
# Measure 0.96 0.96 0.96 0.87
# c-value 0.02 0.02 0.05 0