R. Заменить элементы столбца A, если столбец B начинается с символа

#r #dataframe #replace

#r #фрейм данных #заменить

Вопрос:

У меня есть фрейм данных A (реальный A имеет 1 000 000 строк):

 model    term
2    SEX
2    GAN
2    GT_rs354
6    SEX
6    GAN
6    GT_rs222
3    SEX
3    GAN
3    GT_rs87623
  

Используя R, я хочу создать новый столбец «SNP»: всякий раз, когда в столбце «term» есть элемент, начинающийся с «GT_», я хочу, чтобы новый столбец «SNP» заменял все вхождения «model» соответствующим элементом «GT_x». Я бы получил:

 model    term    SNP
2    SEX    GT_rs354
2    GAN    GT_rs354
2    GT_rs354    GT_rs354
6    SEX    GT_rs222
6    GAN    GT_rs222
6    GT_rs222    GT_rs222
3    SEX    GT_rs87623
3    GAN    GT_rs87623
3    GT_rs87623    GT_rs87623
  

Комментарии:

1. Есть ли какие-либо model , соответствующие двум или более term s, которые начинаются с GT_ ?

2. Привет @ekoam. Нет, нет

Ответ №1:

Решение dplyr

 library(dplyr)
df %>% group_by(model) %>% mutate(SNP = term[which(grepl("^GT_", term))])
  

Ответ №2:

Возможно, это работает:

 library(data.table)
library(stringr)
dt <- setDT(df)
dt[, SNP := str_subset(term, 'GT_') , by = model]
  

Ответ №3:

Используя dplyr и stringr

 
library(dplyr)
library(stringr)

A %>%
   group_by(model) %>%
   mutate(SNP = paste(term, collapse = " ")) %>%
   mutate(SNP = str_extract(SNP, "\bGT_\w "))

#> # A tibble: 9 x 3
#> # Groups:   model [3]
#>   model term       SNP       
#>   <dbl> <chr>      <chr>     
#> 1     2 SEX        GT_rs354  
#> 2     2 GAN        GT_rs354  
#> 3     2 GT_rs354   GT_rs354  
#> 4     6 SEX        GT_rs222  
#> 5     6 GAN        GT_rs222  
#> 6     6 GT_rs222   GT_rs222  
#> 7     3 SEX        GT_rs87623
#> 8     3 GAN        GT_rs87623
#> 9     3 GT_rs87623 GT_rs87623
  

Ваши данные

 A <- structure(list(model = c(2, 2, 2, 6, 6, 6, 3, 3, 3), term = c("SEX", 
"GAN", "GT_rs354", "SEX", "GAN", "GT_rs222", "SEX", "GAN", "GT_rs87623"
)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-9L), problems = structure(list(row = 9L, col = "term", expected = "", 
    actual = "embedded null", file = "literal data"), row.names = c(NA, 
-1L), class = c("tbl_df", "tbl", "data.frame")), spec = structure(list(
    cols = list(model = structure(list(), class = c("collector_double", 
    "collector")), term = structure(list(), class = c("collector_character", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1), class = "col_spec"))