首页 > 解决方案 > 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%

所有这些变量都是chars,但我想将Population_2010Growth_Rate_PercentWorld_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))解决方法,但这不起作用(无论如何似乎毫无意义,因为它已经是字符类型)。

我想知道如何在类型之间正确转换(不仅仅是在这里,而是在正确的数据集中使用),所以我需要知道这里出了什么问题。谢谢你的帮助。

标签: r

解决方案


试试这个解决方案。关键是要小心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")

推荐阅读