另一种可能的解决方案基于您自己的尝试,并考虑到您需要转换比示例中更多的列:
d[,-c(1:2)] <- lapply(d[,-c(1:2)],
function(x) as.numeric(gsub('[$,]', '', sub(")", "", sub("(", "-", x, fixed=TRUE), fixed=TRUE))))
这使:
> d
id desc price price2
1 0 apple 1.00 -5.90
2 1 banana -2.25 2.39
3 2 grapes 1.97 -0.95
或者使用 for 循环:
for(i in 3:ncol(d)){
d[[i]] <- as.numeric(gsub('[$,]', '', sub(")", "", sub("(", "-", d[[i]], fixed=TRUE), fixed=TRUE)))
}
或者使用data.table
包裹:
library(data.table)
cols <- names(d)[-c(1:2)]
setDT(d)[, (cols) := lapply(.SD, function(x) as.numeric(gsub('[$,]', '', sub(")", "", sub("(", "-", x, fixed=TRUE), fixed=TRUE)))),
.SDcols = cols]
或者使用dplyr
包裹:
library(dplyr)
d %>%
mutate_all(funs(as.numeric(gsub('[$,]', '', sub(")", "", sub("(", "-", ., fixed=TRUE), fixed=TRUE)))), -c(1:2))
这都会给你相同的结果。
使用数据:
d <- structure(list(id = 0:2, desc = c("apple", "banana", "grapes"),
price = c("$1.00", "($2.25)", "$1.97"),
price2 = c("($5.9)", "$2.39", "($0.95)")),
.Names = c("id", "desc", "price", "price2"), class = "data.frame", row.names = c("1", "2", "3"))