如果为Na,则将该值替换为另一个值-R(地理代码)
我有一个数据帧,如果lat是NA,那么我希望For循环再次查找地理代码,并用数据帧中的值替换它如果为Na,则将该值替换为另一个值-R(地理代码),r,R,我有一个数据帧,如果lat是NA,那么我希望For循环再次查找地理代码,并用数据帧中的值替换它 Country Continent long lat Netherlands Europe NA NA Norway Europe 8.468946 60.47202 Poland Europe 19.145136 51.91944 library(ggmap) geocode("CountryNa
Country Continent long lat
Netherlands Europe NA NA
Norway Europe 8.468946 60.47202
Poland Europe 19.145136 51.91944
library(ggmap)
geocode("CountryName") will give the lat and long result.
如何以编程方式分配R,使其在数据帧中的每一行中运行for循环,并检查NA,如果NA,则获取地理代码,并在数据帧df中替换它
请帮我做这个。谢谢。我的回答基本上与格雷戈评论中提到的相同,但有一个有效的例子 在R中发出下一个命令后:
library(ggmap) # for using command 'geocode'
# setting up a sample dataframe with missing longitudes and latitudes data
df <- data.frame(Country = c('Netherland', 'Norway', 'Poland'),
Continent = rep('Europe', 3),
long = c(NA, 8.468946, 19.145136),
lat = c(NA, 60.47202, 51.91944))
# print the dataframe
df
要修复缺失的经度和纬度,请发出以下命令:
# looking for rows where longitude is missing
missing.long <- is.na(df$long)
# getting the missing longitude for the above TRUE marked rows
df[missing.long, 'long'] <- geocode(as.character(df$Country[missing.long]))$lon
# looking for rows where latitude is missing
missing.lat <- is.na(df$lat)
# getting the missing latitude for the above TRUE marked rows
df[missing.lat, 'lat'] <- geocode(as.character(df$Country[missing.lat]))$lat
# print the dataframe
df
当然,如果经度和纬度数据总是一起丢失,则不必使用单独的
missing.long
和missing.lat
向量。不需要循环missing\u lat=is.na(您的\u数据$lat)
获取缺少的行fill\u in=geocode(您的数据$Country[missing\u lat])
查找所有缺失的国家。我没有这个软件包,但您可能可以找出如何填充数据框,比如you\u data[missing\u lat,“lat”]=fill\u in$lat
。
# looking for rows where longitude is missing
missing.long <- is.na(df$long)
# getting the missing longitude for the above TRUE marked rows
df[missing.long, 'long'] <- geocode(as.character(df$Country[missing.long]))$lon
# looking for rows where latitude is missing
missing.lat <- is.na(df$lat)
# getting the missing latitude for the above TRUE marked rows
df[missing.lat, 'lat'] <- geocode(as.character(df$Country[missing.lat]))$lat
# print the dataframe
df
Country Continent long lat
1 Netherland Europe 5.291266 52.13263
2 Norway Europe 8.468946 60.47202
3 Poland Europe 19.145136 51.91944