David Z
David Z

Reputation: 7041

how to position a string character in R

Suppose I have a string like:

x<-c("bv_bid_bayley_inf_development_f7r","bv_fci_family_care_indicator_f7r")

how can I position the first "_" (a) and the last "_" (b) so that I can substr(x,a,b) in R. Such a output like that:

bid_bayley_inf_development
fci_family_care_indicator

Upvotes: 0

Views: 70

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

You can use regular expressions to extract the substring:

x <- c("bv_bid_bayley_inf_development_f7r", "bv_fci_family_care_indicator_f7r")

sub("[^_]*_(.*)_[^_]*", "\\1", x)
# [1] "bid_bayley_inf_development" "fci_family_care_indicator" 

Upvotes: 1

Ananta
Ananta

Reputation: 3711

for position only,

gregexpr("_",x)

Upvotes: 1

Related Questions