Заменить значения не-NA в определенном столбце значениями из другого столбца в R - PullRequest
1 голос
/ 02 февраля 2020

Я пытаюсь заменить значения в столбце City.x объединяемого фрейма данных значениями в столбце City.y, если в столбце City.y нет NA.

Другими словами, я хотел бы заменить все значения в столбце City.x за исключением NA.

Вот код, который у меня есть:

library(tidyverse)
library(dplyr)

# Import food data
food <-
  read_csv(file = 'https://s3.amazonaws.com/notredame.analytics.data/inspections.csv', 
           col_names=c("ID", 
                       "DBAName", 
                       "AKAName", 
                       "License", 
                       "FacilityType",
                       "Risk",
                       "Address",
                       "City",
                       "State",
                       "ZIP",
                       "InspectionDate",
                       "InspectionType",
                       "Results",
                       "Violations",
                       "Latitude",
                       "Longitude",
                       "Location"), 
           col_types = "icccffcfffcffcddc",
           skip = 1)

# Change InspectionDate from character type to datetime type
food$InspectionDate <- strptime(food$InspectionDate, "%m/%d/%Y")

#Import zipcode data
zipcode <- 
  read_csv('https://s3.amazonaws.com/notredame.analytics.data/zipcode.csv', 
           col_names = c("ZIP",
                         "City", 
                         "State",
                         "Latitude",
                         "Longitude"),
           skip = 1)

# Convert ZIP, City, and State from character type to factor type
zipcode$ZIP <- as.factor(zipcode$ZIP)
zipcode$City <- as.factor(zipcode$City)
zipcode$State <- as.factor(zipcode$State)

#Correct zip codes (told these were incorrect)
food <- food %>%
  mutate(food$ZIP = ifelse("60627", "60827", ZIP))

#Create merged table from food and zipcode tables
mergedtable <- merge(x=food,y=zipcode,by="ZIP",all.x=TRUE)

#new_DF <- mergedtable[is.na(mergedtable$ZIP),]

mergedtable <- mergedtable %>%
  mutate(mergedtable$City.x = ifelse(!is.na(mergedtable$City.y), mergedtable$City.y, mergedtable$City.x))

mergedtable$City.x <- ifelse(!is.na(mergedtable$City.y), mergedtable$City.y, mergedtable$City.x)

Ни одна из двух строк кода в самом конце не делает то, что я хочу. Первая возвращает ошибку:

Error: unexpected '=' in:  
"mergedtable <- mergedtable %>%  
  mutate(mergedtable$City.x ="

Самая последняя строка превращает значения в объединяемой таблице $ City.x в числа, и я не уверен, откуда эти числа.

1 Ответ

1 голос
/ 02 февраля 2020

Было бы проще с coalesce

library(dplyr)
mergedtable2 <- mergedtable %>%
                     mutate(ZIP = coalesce(City.y, City.x))

В коде ОП нам нужно только имя без кавычек ('ZIP'), чтобы создать новый столбец

mergedtable %>%
         mutate(ZIP = ifelse(!is.na(City.y), City.y, City.x))
                ^^^

Аналогично

food <- food %>%
              mutate(ZIP = ifelse("60627", "60827", ZIP))
                     ^^^
...