3

I have a vector like below

vec <- c("abc\edw\www", "nmn\ggg", "rer\qqq\fdf"......)

I want to remove everything after as soon as first slash is encountered, like below

newvec <- c("abc","nmn","rer")

Thank you.

My original vector is as below (only the head)

[1] "peoria ave\nste \npeoria"                      [2]   "wood dr\nphoenix"                                  
"central ave\nphoenix"                            
[4] "southern ave\nphoenix"                         [5]   "happy valley rd\nste   
\nglendaleaz "               "the americana at brand\n americana way\nglendale"

Here the problem is my original csv file does not contain backslashes, but when i read it backslashes appear. Original csv file is as below

[1] "peoria ave               [2] "wood dr
     nste                          nphoenix"       
     npeoria"

As you can see, they are actually separated by "ENTER" but when i read it in R using read.csv() they are replaced by backslashes.

Ayush Raj Singh
  • 863
  • 5
  • 16
  • 20
  • 1
    You should edit your string to show how it is actually represented in `r`, (i.e. escaped backslashes ``\\``) – Simon O'Hanlon Jun 19 '13 at 09:31
  • The code you provided cannot be reproduced in R. plus you talk about slashes and provide backslash? if you want to add backslashes u should double them. like `vec <- c("abc\\edw\\www")` – Sander Van der Zeeuw Jun 19 '13 at 09:32
  • @SanderVanderZeeuw I have provided more information, please go through it. I think the backslashes are not actually there. They appear when I read them in R. – Ayush Raj Singh Jun 19 '13 at 09:43
  • @user2474387 try to use `read.table('blabla.csv',sep=",")` – Sander Van der Zeeuw Jun 19 '13 at 09:47
  • Before you do anything to your data, please try `cat(vec, sep="\n")` and check what you get. I suspect the data is just fine, and you're getting confused by `print`'s use of `\n` to represent newlines. – Hong Ooi Jun 19 '13 at 15:08

3 Answers3

4

another solution :

 sub("\\\\.*", "", x)
eddi
  • 49,088
  • 6
  • 104
  • 155
droopy
  • 2,788
  • 1
  • 14
  • 12
1
vec <- c("abc\\edw\\www", "nmn\\ggg", "rer\\qqq\\fdf")
sub("([^\\\\])\\\\.*","\\1", vec)
[1] "abc" "nmn" "rer"
user1609452
  • 4,406
  • 1
  • 15
  • 20
1

strssplit(vec, "\\\\") should do the job.

TO select the first element [[1]][1] 2nd [[1]][2]

Sander Van der Zeeuw
  • 1,092
  • 1
  • 13
  • 35