【问题标题】:Merging two dataframes with left_join produces NAs in 'right' columns将两个数据框与 left_join 合并会在“右”列中产生 NA
【发布时间】:2021-04-23 01:57:36
【问题描述】:

当我使用 dplyr::left_join 组合 2 个数据框时,所有“右”数据框列都填充有 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。 我的总体目标是按肯尼亚县名合并所有三个数据集(作物、家庭和性别)。

我可以使用一些帮助。谢谢。

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

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

    "Kenya   "
    "Mombasa   "
    

    left_join 之前添加这个额外的行来修复它:

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

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      相关资源
      最近更新 更多