将舍入函数应用于数据框中的每个元素

She*_*kar 5 loops r

假设我在R中有一个像这样的数据框

x = c(2, 3.432, 5)
y = c(4.5345, NA, "text")
z = c(8.13451, 3.12451, 6.12341)
A = data.frame(x, y, z)
Run Code Online (Sandbox Code Playgroud)

如何将舍入函数应用于数据框的适当元素?本质上我想:

  • 检查元素是否为数字
  • 如果没有,则保持不变
  • 如果是数字,则将其舍入到小数点后三位

我在很多地方都读过,在R中循环不是一个好主意。

A$y[is.numeric(A$y)] <- round(A$y, digits = 3)
Run Code Online (Sandbox Code Playgroud)

不起作用

akr*_*run 3

我们可以尝试lapply

A[] <- lapply(A, function(x) if(is.numeric(x)) round(x, 3) else x)
Run Code Online (Sandbox Code Playgroud)

character/factor如果我们还需要更改具有类列的数字元素的格式

A[] <- lapply(A, function(x) {
           x1 <- type.convert(as.character(x), as.is=TRUE)
    ifelse(grepl("^[0-9.]+$", x1), round(as.numeric(x1), 3), x1)})
Run Code Online (Sandbox Code Playgroud)