在 R 中转换时只有一些字符变为数字
only some characters change to numeric when converting in R
我需要在不添加 NA 的情况下将以下数据框中的 Votes 列变量从字符转换为数字
> 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" ...
我在 Whosebug 上找到了这个 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
如何确保投票栏中的所有数字都转换为数字?
逗号被删除了,您需要先使用 gsub
将其删除。
res$Votes <- as.numeric(gsub(",", "", res$Votes))
要转换具有逗号、美元符号或类似格式的数字,请使用 readr 包中的 parse_number()
。
> library(readr)
> parse_number("28,599")
[1] 28599
我需要在不添加 NA 的情况下将以下数据框中的 Votes 列变量从字符转换为数字
> 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" ...
我在 Whosebug 上找到了这个 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
如何确保投票栏中的所有数字都转换为数字?
逗号被删除了,您需要先使用 gsub
将其删除。
res$Votes <- as.numeric(gsub(",", "", res$Votes))
要转换具有逗号、美元符号或类似格式的数字,请使用 readr 包中的 parse_number()
。
> library(readr)
> parse_number("28,599")
[1] 28599