我有一个df,其中第2列及其他列是美元金额,例如$ 1004.23,($ 1482.40),$ 2423.94等。类似于以下示例:
> df
id desc price
1 0 apple $1.00
2 1 banana ($2.25)
3 2 grapes $1.97
我想先将括号中的数字转换为负数,然后去除美元符号的数字。
for(i in 2:ncol(df)){
df[[i]] <- as.character(sub(")", "", sub("(", "-", df[[i]], fixed=TRUE), fixed=TRUE))
df[[i]] <- as.numeric(gsub('[$,]', '', as.character(df[[i]])))
}
目前,我的代码几乎可以实现我想要的功能。我不想要/不需要的一件事就是四舍五入。每当我运行代码时,它也会四舍五入以使上述df变为:
> df
id desc price
1 0 apple 1
2 1 banana -2
3 2 grapes 2
关于如何在不四舍五入的情况下实现目标的任何建议?它与以后的大量计算混乱。
另一种可能的解决方案基于您自己的尝试,并考虑到您需要转换比示例更多的列:
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"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句