[R] Turning a string into a real vector

arun smartpink111 at yahoo.com
Mon Sep 23 20:36:45 CEST 2013


Hi

If I use your code:
grep ("ACC", input, FALSE, FALSE, TRUE)
#[1] "ACC,1.1,2.2,3.3,4.4\nACC,2.2,3,4,5\nADN,3.3,4,5\nACC,4.4,5.5,6.6,7.7\nADN,5.5,6,7\n"
Seems like you forgot one line of code: with ?strsplit()

vec1<- grep("ACC",strsplit(input,"\n")[[1]],FALSE,FALSE,TRUE)
vec1
#[1] "ACC,1.1,2.2,3.3,4.4" "ACC,2.2,3,4,5"       "ACC,4.4,5.5,6.6,7.7"

 vec2<- grep("ADN",strsplit(input,"\n")[[1]],FALSE,FALSE,TRUE)
vec2
#[1] "ADN,3.3,4,5" "ADN,5.5,6,7"
length(vec2)
#[1] 2


A.K.



I have the following string input: 

input <- "ACC,1.1,2.2,3.3,4.4\nACC,2.2,3,4,5\nADN,3.3,4,5\nACC,4.4,5.5,6.6,7.7\nADN,5.5,6,7\n" 

Note that \n is a real line feed in the data and the numbers are
 all made up and might be other values. The key is that the first number
 is a float, the ACC packets are all floats and the ADN the first value 
is a float and the rest are ints. 

I want to turn this string into a vector of packets. I tired 
using grep and regexpr without luck. I would also like to filter the 
packets so that I can get a vector of just the ACC packets and another 
vector of just the ADN packets. 

When I tried this: 

grep ("ACC", input, FALSE, FALSE, TRUE) 

What I ended up with was: 

[1] "ACC,1.1,2.2,3.3,4.4"            "ACC,2.2,3,4,5"         
"ADN,3.3,4,5"                    "ACC,4.4,5.5,6.6,7.7"           
"ADN,5.5,6,7" 

What I wanted was: 

[1] "ACC,1.1,2.2,3.3,4.4" 
[2] "ACC,2.2,3,4,5" 
[3] "ACC,4.4,5.5,6.6,7.7" 

Then I wanted to put in grep ("ADN", input, FALSE, FALSE, TRUE) and get out: 

[1] "ADN,3.3,4,5" 
[2] "ADN,5.5,6,7" 

Can someone help me figure this out?



More information about the R-help mailing list