Skip to content

list substring

7 messages · Jorge Ivan Velez, Dimitris Rizopoulos, Wacek Kusnierczyk +1 more

#
try this:

x <- c("xxxxx1", "xxxxx2", "yyyyx3")
substr(x, 1, 4)


Best,
Dimitris
calpeda wrote:

  
    
#
calpeda wrote:
sub('^(\\d{4}).*', '\\1', x, perl=TRUE)

vQ
#
thank you,
but I m importing data from a txt file and I have a matrix of n*1
The function str seems to work only from 1*n
Wacek Kusnierczyk wrote:

  
    
#
calpeda wrote:
you see, it would help if you provided more details from the start.  you
may still need to do it;  it seems that both solutions you were given
(mine and the substr one) work for both n*1 and 1*n matrices:

    # 5*1
    (strings = matrix(as.character(sample(10^6, 5)), ncol=1))
   
    substr(strings, 1, 4)
    substr(t(strings), 1, 4)

with a fixed pattern of four digits from the beginning of the string,
the substr solution is better -- simpler and a few times faster.

vQ
#
I was suggested to use

x = data.frame(string = c( "xxxxx1", "xxxxx2", "yyyyx3"))
 x

 apply(x,1,substr,1,4) 

and it's worked good!
Thank you all
Wacek Kusnierczyk wrote: