簡體   English   中英

在 R 中創建具有字符串模式組合的新列

[英]Creating new columns with combinations of string patterns in R

我有一個數據框 - 在其中我有一列用_分隔的長字符串。 現在我有興趣從長字符串中計算模式和幾種可能的組合。 在我下面提供的用例中,您會發現我想計算事件 A 和 B 的發生,但不計算其他任何東西。

如果 A 和 B 像A_BB_A單獨重復,或者如果它們重復n次,我想計算它們,以及這些組合是否多次出現。

示例數據框:

participant <- c("A", "B", "C")
trial <- c(1,1,2)
string_pattern <- c("A_B_A_C_A_B", "B_A_B_A_C_D_A_B", "A_B_C_A_B")

df <- data.frame(participant, trial, string_pattern)

預期輸出:

   participant   trial  string_pattern   A_B  B_A  A_B_A  B_A_B B_A_B_A 
1. A               1    A_B_A_C_A_B      2    1    1      0     0
2. B               1    B_A_B_A_C_D_A_B  2    2    1      1     1
3. C               2    A_B_C_A_B        2    0    0      0     0

我的代碼:


revised_df <- df%>%
                 dplyr::mutate(A_B = stringr::str_count(string_pattern, "A_B"),
                               B_A = stringr::str_count(string_pattern, "B_A"),
                               B_A_B = string::str_count(string_pattern, "B_A_B"))

隨着組合數量的增加,我的方法變得復雜。 因此,尋找更好的解決方案。

你可以寫一個函數來解決這個問題:

m <- function(s){
  a <- seq(nchar(s)-1)
  start <- rep(a, rev(a))
  stop <- ave(start, start, FUN = \(x)seq_along(x)+x)
  b <- substring(s, start, stop)
  gsub('(?<=\\B)|(?=\\B)', '_', b, perl = TRUE)
}

n <- function(x){
  names(x) <- x
  a <- strsplit(gsub("_", '', gsub("_[^AB]+_", ':', x)), ':')
  b <- t(table(stack(lapply(a, \(y)unlist(sapply(y, m))))))
  data.frame(pattern=x, as.data.frame.matrix(b), row.names = NULL)
}
  

n(string_pattern)
          pattern A_B A_B_A B_A B_A_B B_A_B_A
1     A_B_A_C_A_B   2     1   1     0       0
2 B_A_B_A_C_D_A_B   2     1   2     1       1
3       A_B_C_A_B   2     0   0     0       0

嘗試:這會檢查每個字符串行的當前列名


library(dplyr)

df |> 
  mutate(A_B = 0, B_A = 0, A_B_A = 0, B_A_B = 0, B_A_B_A = 0) |> 
  mutate(across(A_B:B_A_B_A, ~ str_count(string_pattern, cur_column())))
  participant trial  string_pattern A_B B_A A_B_A B_A_B B_A_B_A
1           A     1     A_B_A_C_A_B   2   1     1     0       0
2           B     1 B_A_B_A_C_D_A_B   2   2     1     1       1
3           C     2       A_B_C_A_B   2   0     0     0       0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM