在R中随机化后重新填充关系数据框中的列

时间:2016-04-05 05:57:23

标签: r relational-database filtering conditional-formatting

我有一个个人及其配偶的数据框,其中包含我用plyr :: mapvalues随机化的一些个人信息(即姓氏),以保护身份。这是一个可重复的例子,说明在改变姓氏之前和之后的表现:

# before
d <- data.frame(id = c(1:6), 
                first_name = c('Jeff', 'Marilyn', 'Gwyn', 
                               'Alice', 'Sam', 'Sarah'), 
                surname = c('Goldbloom', 'Monroe', 'Paltrow', 'Goldbloom',
                            'Smith', 'Silverman'), 
                spouse_id = c(2, 1, 1, 5, 4, "NA"), 
                spouse = c('Marilyn Monroe', 'Jeff Goldbloom', 'Jeff Goldbloom', 
                           'Sam Smith', 'Alice Goldbloom', 'NA'))
d
> id first_name   surname spouse_id          spouse
   1       Jeff Goldbloom         2  Marilyn Monroe
   2    Marilyn    Monroe         1  Jeff Goldbloom
   3       Gwyn   Paltrow         1  Jeff Goldbloom
   4      Alice Goldbloom         5       Sam Smith
   5        Sam     Smith         4 Alice Goldbloom
   6      Sarah Silverman        NA              NA

# replacement names to serve as surnames (doesn't matter what they are, just
 that the ratios remain the same as before; mapvalues takes care of this)

repnames <- c("Arman"   , "Clovis"  , "Garner"  , "Casey"  ,  "Birch")
s <- unique(d$surname)
d$surname <- plyr::mapvalues(d$surname, from = s, to = repnames) #replace surnames

# After replacement, the dataframe looks like:
d
>   id first_name surname spouse_id          spouse
    1       Jeff   Arman         2  Marilyn Monroe
    2    Marilyn  Clovis         1  Jeff Goldbloom
    3       Gwyn  Garner         1  Jeff Goldbloom
    4      Alice   Arman         5       Sam Smith
    5        Sam   Casey         4 Alice Goldbloom
    6      Sarah   Birch        NA              NA

每个人都有自己的id号码,但不是所有人都有配偶。如果某人确实有配偶,则其配偶的个人id会反映在spouse_id列中。我这样做是为了以后可以使用像dplyr::filter(d, spouse %in% spouse_id)这样的东西分别过滤个人及其配偶。

我的问题是,如何使用关系idspouse_id列重新填充spouse列,以便它反映新的随机姓氏?即最终预期产出为:

  id first_name surname spouse_id         spouse
  1       Jeff   Arman         2     Marilyn Clovis
  2    Marilyn  Clovis         1     Jeff Arman
  3       Gwyn  Garner         1     Jeff Arman
  4      Alice   Arman         5     Sam Casey
  5        Sam   Casey         4     Alice Arman
  6      Sarah   Birch        NA             NA
  

...因此,first_namesurname列会涉及一些连接。我从来没有在R中做过那么有条件的东西 - 在Excel中我想它会嵌套VLOOKUP函数......

谢谢,抱歉,它非常具体,但希望它能为那里的某个人带来一个有趣的挑战。

1 个答案:

答案 0 :(得分:1)

假设您的NAs是实际的NA,那么

d$spouse <- paste(d$first_name, d$surname)[d$spouse_id]
d$spouse
#[1] "Marilyn Clovis" "Jeff Arman"     "Jeff Arman"     "Sam Casey"      "Alice Arman"    NA