簡體   English   中英

將兩個數據框與 left_join 合並會在“右”列中產生 NA

[英]Merging two dataframes with left_join produces NAs in 'right' columns

當我使用 dplyr::left_join 組合 2 個數據幀時,所有“右”dataframe 列都填充有 NA 值。

我已經檢查了 StackOverflow 上的多個其他答案,以嘗試消除我的錯誤來源,包括https://stackoverflow.com/questions/35016377/dplyrleft-join-produce-na-values-for-new-joined-columns]

但是,Stack 上已有的答案無法解決我的問題。

這是我的可重現代碼

# Libraries
library('remotes')
library("tidytuesdayR")
library('ggplot2')
library("tidyverse")

# Load data
tuesdata <- tidytuesdayR::tt_load('2021-01-19')
gender <- tuesdata$gender
crops <-tuesdata$crops
households <- tuesdata$households

#rename crops column
colnames(crops)[1]<-"County"
# make County columns into characters
gender$County <- as.character(gender$County)
crops$County <- as.character(crops$County)
households$County <- as.character(households$County)
# Change "total" cell to "kenya"
gender[1, 1] <- "Kenya"
# All caps to Title case
crops$County<-str_to_title(crops$County)

# left_join households and crops column
df<- left_join(households, crops, by=c("County"="County")) 

當我運行它時,每個“crops”列都充滿了 NA。 我的總體目標是按肯尼亞縣名合並所有三個數據集(作物、家庭和性別)。

我可以使用一些幫助。 謝謝。

您需要修剪households df 中的County變量 - 有多余的空格,因此它與crops df 不正確匹配。 例如:

"Kenya   "
"Mombasa   "

left_join修復它之前添加這個額外的行:

households$County <- stringr::str_trim(households$County)
df <- left_join(households, crops) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM