11

从 Wikipedia 导入表格后,我有以下形式的值列表:

    > tbl[2:6]
    $`Internet
    Explorer`
     [1] "30.71%" "30.78%" "31.23%" "32.08%" "32.70%" "32.85%" "32.04%" "32.31%" "32.12%" "34.07%" "34.81%"
    [12] "35.75%" "37.45%" "38.65%" "40.63%" "40.18%" "41.66%" "41.89%" "42.45%" "43.58%" "43.87%" "44.52%"

    $Chrome
     [1] "36.52%" "36.42%" "35.72%" "34.77%" "34.21%" "33.59%" "33.81%" "32.76%" "32.43%" "31.23%" "30.87%"
    [12] "29.84%" "28.40%" "27.27%" "25.69%" "25.00%" "23.61%" "23.16%" "22.14%" "20.65%" "19.36%" "18.29%"

我试图摆脱百分比符号,以便将数据转换为数字形式。

有没有比矢量化更快的方法来清理这些数据?我当前的代码如下:

    data <- lapply(tbl[2:6], FUN = function(x) as.numeric(gsub("%", "", x)))

数据最终成为数据框,但我无法gsub在数据框的所有元素上正常工作。有没有办法 gsub() 数据框的每个元素?

该项目的代码是在线的,有结果。提前致谢!

4

3 回答 3

12

好吧,我认为您可以通过以下方式进行操作,但我不知道它是否比您的更好或更清洁:

df <- data.frame(tbl)
df[,-1] <- as.numeric(gsub("%", "", as.matrix(df[,-1])))

这使 :

R> head(df)
            Date Internet.Explorer Chrome Firefox Safari Opera Mobile
1   January 2013             30.71  36.52   21.42   8.29  1.19  14.13
2  December 2012             30.78  36.42   21.89   7.92  1.26  14.55
3  November 2012             31.23  35.72   22.37   7.83  1.39  13.08
4   October 2012             32.08  34.77   22.32   7.81  1.63  12.30
5 September 2012             32.70  34.21   22.40   7.70  1.61  12.03
6    August 2012             32.85  33.59   22.85   7.39  1.63  11.78
R> sapply(df, class)
             Date Internet.Explorer            Chrome           Firefox 
         "factor"         "numeric"         "numeric"         "numeric" 
           Safari             Opera            Mobile 
        "numeric"         "numeric"         "numeric" 
于 2013-02-14T09:17:44.890 回答
4

像 juba 我不确定这种方式是否“更好或更清洁”但是......要对数据框的所有元素采取行动,您可以使用apply

# start with data frame, not list
url <- "http://en.wikipedia.org/wiki/Usage_share_of_web_browsers"
# Get the eleventh table.
tbl <- readHTMLTable(url, which = 11, stringsAsFactors = F)

# use apply on the non-date columns
tbl[, 2:7] <- apply(tbl[, 2:7], 2, function(x) as.numeric(gsub("%", "", x)))
于 2013-02-14T10:18:28.607 回答
0

我会通过使用for-loop 来做到这一点(我知道人们不太喜欢循环,但至少它不会触及您的数据结构):

 for (i in 1:length(tbl[2:6])) {
         tbl[,i] <- gsub("%", "", tbl[,i])
 }
于 2021-11-29T15:15:00.110 回答