【问题标题】:Determine the value of a variable present in dataset A but not in dataset B (which is exactly the same as dataset A except for this variable)确定数据集 A 中存在但数据集 B 中不存在的变量的值(与数据集 A 完全相同,但此变量除外)
【发布时间】:2021-08-17 17:40:44
【问题描述】:

我有两个相同的数据集,除了一个变量。例如,如下所示,我有两个名为 boys_missboys_miss2 的数据集。 boys_miss2 有一个额外的二进制变量(称为类型),boys_miss 没有。所以我想使用两个数据集中的观察变量来确定boys_miss 中的type 变量。我不确定这样做的最佳方法是什么。任何解决方案或建议将不胜感激。

# loads relevant packages using the pacman package
pacman::p_load(
  mice)        # for boys dataset


# set seed
set.seed(2347723) 


# generate a samall sample of the boys dataset
boys_miss <- sample(head(boys,100))

# create other dataset that has out variable of interest
boys_miss2 <- boys_miss[sample(1:nrow(boys_miss)), ] 

# create the variable of interest
boys_miss2$type <- as.factor(sample(c("runner", "swimmer"), 
                           size = nrow(boys_miss2), 
                           replace = TRUE, 
                           prob = c(.76, .24)))




# Goal here is to replicate type variable in `boys_miss` dataset using the values the matching 
# in `boys_miss` and `boys_miss2`

【问题讨论】:

    标签: r database dplyr data-wrangling


    【解决方案1】:

    尝试在两列的pasteed 字符串上使用match,使用索引返回相应的“类型”值

    boys_miss$type <- boys_miss2$type[match(do.call(paste, boys_miss), 
          do.call(paste, boys_miss2[-ncol(boys_miss2)]))]
    

    【讨论】:

    • 这适用于上面的数据集,但不适用于包含 18,000 行的大型数据集。除了行数和列数之外,不确定这里会有什么不同。
    猜你喜欢
    • 1970-01-01
    • 2014-12-04
    • 2015-01-17
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多