更改Paste0 Min Max以创建新的id变量

时间:2020-11-02 15:12:05

标签: dplyr mutate

如果contact_id和Relationship_id的组合相同,并且位置相同,我需要创建一个id来将contact_id和Relationship_id之间的关系定义为一个普通的family_id。

样本数据

account_id <- c(1,1,1,1)
contact_id <- c(1234,2345,3456,4567)
relationship_id <- c(2345,1234,NA,"")
ownership_percent <- c(26,22,40,12)
score <- c(500,300,700,600)
testdata <- data.frame(account_id,contact_id,relationship_id,ownership_percent,score)

一直使用mutate,paste0,min,max,group_indices的组合-找不到正确的组合,被NA绊倒,并订购了新的family_id。

方法1

  library(dplyr)
    testdata %>%
      mutate(col1 = pmin(contact_id, relationship_id), 
             col2 = pmax(contact_id, relationship_id),
             household_id = paste0(col1,col2)) %>%

方法2

 testdata %>%
    mutate(household_id = sort(paste0(c(contact_id, relationship_id))), collapse = "")

错误:列household_id的长度必须为4(行数)或1,而不是8

预期结果

enter image description here

1 个答案:

答案 0 :(得分:0)

sed -En 's/^([^;]*;).*(TEST-136=[^,]*).*/\1\2/p' file