【发布时间】: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 并提供了一些建议 我尝试了以下方法
-
使用
transformD <- transform(res, Votes = as.numeric(Votes))但是,这只会导致少数数字转换为数字。见下文
1 NA 2 NA 3 254 4 753 5 NA 6 NA 7 NA -
使用
as.character,然后使用as.numericas.numeric(as.character(res$Votes))但这会导致同样的问题
NA NA 254 753 NA NA NA
如何确保投票栏中的所有数字都转换为数字?
【问题讨论】:
-
先去掉逗号:
sub(",", "", res$Votes)。然后as.numeric/as.character.
标签: r type-conversion na