Can I use gsub() on each element of a data frame?

前端 未结 2 494
醉话见心
醉话见心 2020-12-16 17:27

After importing a table from Wikipedia, I have a list of values of the following form:

    > tbl[2:6]
    $`Internet
    Explorer`
     [1] \"30.71%\" \"3         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 18:19

    Like juba I'm uncertain if this way is "better or cleaner" but...to act on all elements of a data frame, you can use 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)))
    

提交回复
热议问题