我的问题似乎就这么简单,但是我不明白哪里出了问题。
我有以下数据:
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"
我希望将所有元素四舍五入到选定的位数。我不能简单地应用舍入函数,因此我编写了以下函数:
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)时,它不返回四舍五入的数字。怎么了?我应该使用另一个套用功能吗?我应该将列表转换为例如数据框吗?
你有一个清单。不要使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句