This uses base R's gregexpr
, regmatches
, and regmatches<-
to round any number with a decimal part.
It will work correctly even for numbers like .789
(i.e. with no digits before the decimal point) and -0.4
(which should round to a number without a minus sign). The one situation where it might perform less than ideally is that it will not remove the trailing decimal from a number like 10.
.
string <- c("a.name & $-436.735 $ & $-710.832$ \\\\",
"std(a.name) & $(1403.604)$ & $(1274.283)$ \\\\")
f <- function(x) {
pat <- "(-)?[[:digit:]]+\\.[[:digit:]]*"
m <- gregexpr(pat, x)
regmatches(x,m) <- lapply(regmatches(x,m), function(X) round(as.numeric(X)))
x
}
f(string)
# [1] "a.name & $-437 $ & $-711$ \\\\"
# [2] "std(a.name) & $(1404)$ & $(1274)$ \\\\"