r - R `as.numeric` 将所有值更改为 NA
问题描述
我有一些从网上导入的简单数据,用于了解该fread()
功能。它导入得很好,而且我有一个关于各大洲人口的小而干净的数据集:
> continent_populations
Rank Continent Population_2010 Growth_Rate_Percent World_Pop_Percent
1: 1 Asia 4.581.757.408 1.04% 59.69%
2: 2 Africa 1.216.130.000 2.57% 16.36%
3: 3 Europe 738.849.000 0.08% 9.94%
4: 4 North America 579.024.000 0.96% 7.79%
5: 5 South America 422.535.000 1.04% 5.68%
6: 6 Oceania 38.304.000 1.47% 0.54%
7: 7 Antarctica 1.106 0 <0.01%
所有这些变量都是char
s,但我想将Population_2010
、Growth_Rate_Percent
和World_Pop_Percent
变量转换为数字。我开始只是使用transform()
:
transform(continent_populations, Population_2010 = as.numeric(Population_2010))
NA
但是,我收到了已引入值的警告;现在所有的值都是 NA。我在上一个线程中读到Population_2010
,至少对于我的变量,使用逗号分隔符而不是句点可能会导致错误,因此我将它们换成了句点:
continent_populations$Population_2010 <- gsub(",", ".", continent_populations$Population_2010)
但是,as.numeric()
仍将所有值转换为 NA。对于其他两个变量,我假设需要删除百分号。首先,我只是对为什么Population_2010
变量不会转换感到困惑。我也尝试了建议的as.numeric(as.character(var))
解决方法,但这不起作用(无论如何似乎毫无意义,因为它已经是字符类型)。
我想知道如何在类型之间正确转换(不仅仅是在这里,而是在正确的数据集中使用),所以我需要知道这里出了什么问题。谢谢你的帮助。
解决方案
试试这个解决方案。关键是要小心gsub()
并使用正确的符号进行替换。此外,您可以使用trimws()
以删除值中的任何空格。这里的代码:
#Code
#First remove dots from population
df$Population_2010 <- trimws(gsub('.','',df$Population_2010,fixed=T))
#Second remove percent symbol
df$Growth_Rate_Percent <- trimws(gsub('%','',df$Growth_Rate_Percent,fixed=T))
#Finally remove percent and < symbols
df$World_Pop_Percent <- trimws(gsub('%|<','',df$World_Pop_Percent))
#Transform to numeric
df$Population_2010 <- as.numeric(df$Population_2010)
df$Growth_Rate_Percent <- as.numeric(df$Growth_Rate_Percent)
df$World_Pop_Percent <- as.numeric(df$World_Pop_Percent)
str(df)
输出:
str(df)
'data.frame': 7 obs. of 4 variables:
$ Continent : chr "Asia" "Africa" "Europe" "NorthAmerica" ...
$ Population_2010 : num 4.58e+09 1.22e+09 7.39e+08 5.79e+08 4.23e+08 ...
$ Growth_Rate_Percent: num 1.04 2.57 0.08 0.96 1.04 1.47 0
$ World_Pop_Percent : num 59.69 16.36 9.94 7.79 5.68 ...
使用的一些数据:
#Data
df <- structure(list(Continent = c("Asia", "Africa", "Europe", "NorthAmerica",
"SouthAmerica", "Oceania", "Antarctica"), Population_2010 = c(4581757408,
1216130000, 738849000, 579024000, 422535000, 38304000, 1106),
Growth_Rate_Percent = c(1.04, 2.57, 0.08, 0.96, 1.04, 1.47,
0), World_Pop_Percent = c(59.69, 16.36, 9.94, 7.79, 5.68,
0.54, 0.01)), row.names = c("1", "2", "3", "4", "5", "6",
"7"), class = "data.frame")
推荐阅读
- java - 如何打印和加载带有随机数的数组
- aws-lambda - 如何在 AWS lambdas 中保持状态?
- swift - 删除 Swift 5 中的转义“\”字符
- javascript - 我需要使用 JavaScript 或 HTML 链接到当前 HTML 页面中的另一个 HTML 页面
- apache - 基于健康检查 URL 的热备故障转移 Apache 模块
- python - python:MTCNN 没有保存所有文件
- java - getDeclaredMethods() + 创建数组 = 额外方法?
- .net-core - 在 asp.net core/grpc 集成测试中使用 HttpTest
- arrays - 在VBA中的动态范围数组上使用排序函数?
- elasticsearch - 设置 scaling_factor 参数时的奇怪行为