Hi,
I want to extract value in row using r .can anyone advise .
I need to extract (AP2468 ) value from below row after SUB ACCT :
Missing subac :HHH90FF1 in parameter setup for SUB ACCT : AP2468 SOURCE : LOAD_POETS : MISSING TRADE LINK
Hi,
I want to extract value in row using r .can anyone advise .
I need to extract (AP2468 ) value from below row after SUB ACCT :
Missing subac :HHH90FF1 in parameter setup for SUB ACCT : AP2468 SOURCE : LOAD_POETS : MISSING TRADE LINK
Below you will find different solutions for your request based on the 'stringr' package (CHEAT SHEET). It's a quite cool package with a lot of nice options for string modification. Otherwise R-base function as grep(), gsub(), strsplit(), substr() etc. are also available, just try it out.
library(stringr)
#different ways to extract values of interest out of a vector
get.AP.v1 <- function(x){
x <- str_replace_all(x, pattern = ' : | :|: ',replacement = ':')
x.start <- str_locate(x, pattern = 'ACCT:')[,2]
x.end <- str_locate(x, pattern = 'SOURCE:')[,1]
x <- str_sub(x, start = x.start+1, end = x.end-1)
return(str_trim(x))
}
get.AP.v2 <- function(x){
x <- unlist(str_split(x, pattern = ':'))
x <- x[str_detect(x, pattern = 'SOURCE')]
x <- str_replace(x, pattern = 'SOURCE', replacement = '')
return(str_trim(x))
}
get.AP.v3 <- function(x){
x <- str_extract(x, '(?<=ACCT : )\\w+')
return(x)
}
#run your expample and get value of interest
x <- c('Missing subac :HHH90FF1 in parameter setup for SUB ACCT : AP2468 SOURCE : LOAD_POETS : MISSING TRADE LINK',
'Missing subac :HHH90FF1 in parameter setup for SUB ACCT : AP3456 SOURCE : LOAD_POETS : MISSING TRADE LINK',
'Missing subac :HHH90FF1 in parameter setup for SUB ACCT : BP9876 SOURCE : LOAD_POETS : MISSING TRADE LINK',
'Missing subac :HHH90FF1 in parameter setup for SUB ACCT : XP1122 SOURCE : LOAD_POETS : MISSING TRADE LINK')
get.AP.v1(x)
#> [1] "AP2468" "AP3456" "BP9876" "XP1122"
get.AP.v2(x)
#> [1] "AP2468" "AP3456" "BP9876" "XP1122"
get.AP.v3(x)
#> [1] "AP2468" "AP3456" "BP9876" "XP1122"
Created on 2019-02-14 by the reprex package (v0.2.1)
As note: Please, try to use 'reprex' in future. It's quite a cool tool to post your questions to the R-communtiy. It helps us to help you!
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.