【问题标题】:only some characters change to numeric when converting in R在 R 中转换时只有一些字符变为数字
【发布时间】:2018-03-03 03:33:51
【问题描述】:

我需要将以下数据框中的 Votes 列变量从字符转换为数字而不添加 NA

 > res
                  Party              Votes                  
 1 Progressive Liberal Party         28,599           
 2    Free National Movement         19,781           
 3 Commonwealth Labour Party            254            
 4              Independents            753            
 5       Invalid/blank votes                             
 6                     Total         49,387            

 > str(res)
'data.frame':   7 obs. of  5 variables:
$ Party: chr  "Progressive Liberal Party" "Free National Movement" 
"Commonwealth Labour Party" "Independents" ...
$ Votes: chr  "28,599" "19,781" "254" "753" ...

我在 StackOverflow 上找到了这个 post 并提供了一些建议 我尝试了以下方法

  • 使用transform

    D <- transform(res, Votes = as.numeric(Votes))
    

    但是,这只会导致少数数字转换为数字。见下文

     1    NA
     2    NA
     3   254
     4   753
     5    NA
     6    NA
     7    NA 
    
  • 使用as.character,然后使用as.numeric

      as.numeric(as.character(res$Votes))
    

    但这会导致同样的问题

    NA  NA 254 753  NA  NA  NA
    

如何确保投票栏中的所有数字都转换为数字?

【问题讨论】:

  • 先去掉逗号:sub(",", "", res$Votes)。然后as.numeric/as.character.

标签: r type-conversion na


【解决方案1】:

逗号正在丢弃,您需要先使用gsub 将其删除。

res$Votes <- as.numeric(gsub(",", "", res$Votes))

【讨论】:

  • 在我上面的评论中,我忘记了gsub返回character,没有必要再次使用它。
【解决方案2】:

要转换具有逗号、美元符号或类似格式的数字,请使用 readr 包中的 parse_number()

> library(readr)
> parse_number("28,599")
[1] 28599

【讨论】:

  • 你也可以一开始就使用readr::read_csv来导入你的CSV文件,避免整个问题。
猜你喜欢
  • 2021-11-17
  • 2020-01-21
  • 2020-12-02
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多