假设我在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)
不起作用
我们可以尝试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)