簡體   English   中英

如何根據條件消除匹配模式

[英]How to eliminate matching pattern based on condition

我有一個3列的數據框,如下所示
I / p數據框

A  =  c("(0_22),(0_25),(1_29)","(1_34),(1_38),(0_40)","(0_07),(0_09),(0_10),(0_13)","(1_47),(1_49),(1_53),(1_57)")
    zero =c(5,NA,6,NA)
    one = c(NA,4,NA,10)
    df = data.frame(A,zero,one)

O / p數據幀

A  =  c("(0_22),(0_25),(1_29)","(1_34),(1_38),(0_40)","(0_07),(0_09),(0_10),(0_13)","(1_47),(1_49),(1_53),(1_57)")
zero =c(5,NA,6,NA)
one = c(NA,4,NA,10)
required_val = c("(1_29)","(0_40)",'','')
df = data.frame(A,zero,one,required_val)

如何基於零和一變量從變量“ A”獲取列“ required_val”

即如果var“ zero”大於0,則消除由(0_)組成的字符串
如果var“ one”大於0,則消除由(1_)組成的字符串

這基本上是一個模式匹配問題:

library(magrittr) # to avoid repeating the long subscript below
df$A <- as.character(df$A) # think this is what you wanted

# get rid of the (0_...) bits:
df$A[! is.na(df$zero) & df$zero > 0] %<>% 
      {gsub("?\\(0_.*?\\)", "", .)} 

# and the (1_...) bits:
df$A[! is.na(df$one) & df$one > 0]   %<>% 
      {gsub("?\\(1_.*?\\)", "", .)}

# now get rid of trailing commas (this was trickiest!)
df$A %<>%
      {gsub(",+$", "", .)} %>%
      {gsub("^,+", "", .)} %>%
      {gsub(",+", ",", .)}

這是一個替代解決方案,

required_val<-NA
for (i in 1:length(A))
{
  required_val[i]<-""

  if(!is.na(zero[i]) & grepl("1_",A[i]))
  {
    required_val[i]<-substr(A[i],unlist(gregexpr('1_',A[i]))[1],unlist(gregexpr('1_',A[i]))[1]+3)
  } else if (!is.na(one[i]) & grepl('0_',A[i]))
  {
    required_val[i]<-substr(A[i],unlist(gregexpr('0_',A[i]))[1],unlist(gregexpr('0_',A[i]))[1]+3)
  } 
}
df = data.frame(A,zero,one,required_val)

使用申請

#example data
df1 <- data.frame(A  =  c("(0_22),(0_25),(1_29)","(1_34),(1_38),(0_40)","(0_07),(0_09),(0_10),(0_13)","(1_47),(1_49),(1_53),(1_57)"),
                  zero = c(5, NA, 6, NA),
                  one = c(NA, 4, NA, 10),
                  stringsAsFactors = FALSE)

cbind(df1,
      required_val = apply(df1, 1,
                           function(i){
                             ix <- which.max(as.numeric(i[2:3]) > 1) - 1
                             x <- unlist(strsplit(i[1], ","))
                             x <- x[ !grepl(paste0("^\\(", ix), x) ]
                             if(length(x) == 0) {x <- ""}
                             #return
                             x
                           }))

#                             A zero one required_val
# 1        (0_22),(0_25),(1_29)    5  NA       (1_29)
# 2        (1_34),(1_38),(0_40)   NA   4       (0_40)
# 3 (0_07),(0_09),(0_10),(0_13)    6  NA             
# 4 (1_47),(1_49),(1_53),(1_57)   NA  10             

暫無
暫無

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

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