简体   繁体   English

R - 组合两个字符向量,然后切断最后一个字符

[英]R - combine two character vectors, then cut off last character

I am handling a large data set which stores a 9-digit ID in two columns, say ID_part_1 and ID_part_2我正在处理一个大型数据集,该数据集将 9 位 ID 存储在两列中,例如ID_part_1ID_part_2

ID part 1 is a common identifier for top-level specification which are duplicated throughout this column and ID part 2 is unique for each ID part 1. I want to combine part 1 with part 2 and then cut off the last character or integer of the generated strings. ID 部分 1 是顶级规范的通用标识符,在本专栏中重复,ID 部分 2 对于每个 ID 部分 1 都是唯一的。我想将部分 1 与部分 2 组合,然后切断最后一个字符或 integer生成的字符串。

See the example data below:请参阅下面的示例数据:

    ID_part_1    ID_part_2    Comb_ID
    G12345       678          G1234567
    G12345       679          G1234567
    A23567       9C1          A235679C
    123456       789          12345678

All data is stored in a data.table, say my_data.dt , so the columns can be addressed easily.所有数据都存储在 data.table 中,例如my_data.dt ,因此可以轻松处理这些列。 Both columns ID_part_1 and ID_part_2 are of type "character". ID_part_1ID_part_2列都是“字符”类型。 The computed results should be stored in column Comb_ID.计算结果应存储在 Comb_ID 列中。 As trimming the last character off the combined string, I will then subsequently extract all unique values from the computed column as:在从组合字符串中修剪最后一个字符时,我随后将从计算列中提取所有唯一值:

unique(my_data.dt[, Comb_ID])

We can use substr with paste in base R我们可以在base R中使用带有pastesubstr

my_data.dt$Comb_ID <- with(my_data.dt,
      paste0(ID_part_1, substr(ID_part_2, 1, 2)))

my_data.dt$Comb_ID
#[1] "G1234567" "G1234567" "A235679C" "12345678"

NOTE: No packages are needed注意:不需要包

data数据

my_data.dt <- structure(list(ID_part_1 = c("G12345", "G12345", "A23567", "123456"
), ID_part_2 = c("678", "679", "9C1", "789"), Comb_ID = c("G1234567", 
"G1234567", "A235679C", "12345678")), class = "data.frame", row.names = c(NA, 
-4L))

An option based in the tidyverse.基于 tidyverse 的选项。

library(dplyr)
library(stringr)
library(purrr)

data %>%
  mutate(Comb_ID = map2_chr(ID_part_1, ID_part_2, ~ str_c(.x, .y, collapse = '')),
         Comb_ID = str_sub(Comb_ID, 1, -2))


#    ID_part_1 ID_part_2  Comb_ID
# 1:    G12345       678 G1234567
# 2:    G12345       679 G1234567
# 3:    A23567       9C1 A235679C
# 4:    123456       789 12345678

Data数据

data <- structure(list(ID_part_1 = c("G12345", "G12345", "A23567", "123456"
), ID_part_2 = c("678", "679", "9C1", "789")), row.names = c(NA, 
-4L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x55dd6c5238e0>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM