我一直在寻找一些在R程序包,以帮助我在把美元值漂亮的数值。 我似乎没有能够找到一个(在plyr包为例)。 我正在寻找的是简单地删除$符号以及分别翻译“M”和“K”的数百万,数千民生之本。
要复制,我可以在下面使用此代码:
require(XML)
theurl <- "http://www.kickstarter.com/help/stats"
html <- htmlParse(theurl)
allProjects <- readHTMLTable(html)[[1]]
names(allProjects) <- c("Category","LaunchedProjects","TotalDollars","SuccessfulDollars","UnsuccessfulDollars","LiveDollars","LiveProjects","SuccessRate")
数据是这样的:
> tail(allProjects)
Category LaunchedProjects TotalDollars SuccessfulDollars UnsuccessfulDollars LiveDollars
8 Food 3,069 $16.79 M $13.18 M $2.78 M $822.64 K
9 Theater 4,155 $13.45 M $12.01 M $1.22 M $217.86 K
10 Comics 2,242 $12.88 M $11.07 M $941.31 K $862.18 K
11 Fashion 2,799 $9.62 M $7.59 M $1.44 M $585.98 K
12 Photography 2,794 $6.76 M $5.48 M $1.06 M $220.75 K
13 Dance 1,185 $3.43 M $3.13 M $225.82 K $71,322
LiveProjects SuccessRate
8 189 39.27%
9 111 64.09%
10 134 46.11%
11 204 27.24%
12 83 36.81%
13 40 70.22%
最后我写我自己的函数:
dollarToNumber <- function(vectorInput) {
result <- c()
for (dollarValue in vectorInput) {
if (is.factor(dollarValue)) {
dollarValue = levels(dollarValue)
}
dollarValue <- gsub("(\\$|,)","",dollarValue)
if(grepl(" K",dollarValue)) {
dollarValue <- as.numeric(gsub(" K","",dollarValue)) * 1000
} else if (grepl(" M",dollarValue)) {
dollarValue <- as.numeric(gsub(" M","",dollarValue)) * 1000000
}
if (!is.numeric(dollarValue)) {
dollarValue <- as.numeric(dollarValue)
}
result <- append(result,dollarValue)
}
result
}
然后,我用它来得到我想要的东西:
allProjects <- transform(allProjects,
LaunchedProjects = as.numeric(gsub(",","",levels(LaunchedProjects))),
TotalDollars = dollarToNumber(TotalDollars),
SuccessfulDollars = dollarToNumber(SuccessfulDollars),
UnsuccessfulDollars = dollarToNumber(UnsuccessfulDollars),
LiveDollars = dollarToNumber(LiveDollars),
LiveProjects = as.numeric(LiveProjects),
SuccessRate = as.numeric(gsub("%","",SuccessRate))/100)
这将给我下面这样的结果:
> str(allProjects)
'data.frame': 13 obs. of 8 variables:
$ Category : Factor w/ 13 levels "Art","Comics",..: 6 8 4 9 12 11 1 7 13 2 ...
$ LaunchedProjects : num 10006 1185 1860 20025 2242 ...
$ TotalDollars : num 1.11e+08 9.68e+07 6.89e+07 6.66e+07 4.31e+07 ...
$ SuccessfulDollars : num 90990000 84960000 59020000 59390000 34910000 ...
$ UnsuccessfulDollars: num 16640000 7900000 6830000 5480000 3700000 ...
$ LiveDollars : num 3090000 3970000 3010000 1750000 4470000 ...
$ LiveProjects : num 13 7 6 11 3 10 8 4 1 2 ...
$ SuccessRate : num 0.394 0.338 0.382 0.541 0.334 ...
我是新来的R和我觉得我写的那么丑,肯定有更好的方法来做到这一点不重新发明轮子的代码? 我使用申请,aaply,没有成功ddply功能(我尽量不使用for循环,以及...)。 最重要的是,与SuccessRate列打交道时,我找不到类似的东西在河的as.percentage功能我缺少什么?
任何指导意见将非常感激!