简体   繁体   English

R 根据其他列的条件分配列的值

[英]R assign value of a column base on other column's condition

I want to apply reverse_geo function if the address is empty and latitude and longitude are not empty.如果地址为空且经纬度不为空,我想申请 reverse_geo function。 The csv file: csv 文件:

latitude纬度 longitude经度 address地址
38.89770 38.89770 -77.03655 -77.03655 Pennsylvania Avenue, Washington, District of columbia, 20045, United States宾夕法尼亚大道,华盛顿,哥伦比亚特区,20045,美国
37.79520 37.79520 -122.40279 -122.40279
41.87535 41.87535

The code I run is:我运行的代码是:

library(tidygeocoder)
library(dplyr)

path <- "mypath"
data <- read.csv (paste (path, "sample2.csv", sep = ""))
data
data<-data %>%
  mutate(address = case_when(address=="" & latitude!="" & longitude!="" ~ reverse_geo(lat = latitude, long = longitude, method = "osm")))

But I got但我得到了

Error in `mutate()`:
! Problem while computing `address = case_when(...)`.
Caused by error:
! Can't use NA as column index with `[` at positions 1, 2, and 3.

Which I can't figure out why.我不知道为什么。

you could do that:你可以这样做:


data$address <- ifelse((is.na(data$address) | data$address == '') & !(is.na(data$latitude) | is.na(data$longitude)), 
              reverse_geo(lat = data$latitude, 
                          long = data$longitude, method = "osm")$address,
              data$address)

or better that:或者更好的是:

library(data.table)

setDT(data)
query_df <- data[(is.na(data$address) | data$address == '') & !(is.na(data$latitude) | is.na(data$longitude)),]
query_df$address <- reverse_geo(lat = query_df$latitude, 
                                long = query_df$longitude, method = "osm")$address

data <- merge(data, query_df[!is.na(address),], by = c("latitude", "longitude"), all = TRUE)
data$address <- ifelse(is.na(data$address.y), data$address.x, data$address.y)
data$address.x <- NULL
data$address.y <- NULL

because first suggestion is going to load the server with useless queries.因为第一个建议是用无用的查询加载服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM