Richard
Richard

Reputation: 61259

R perform grep on input

I have a file with the following contents

3594 -124.049541 44.429077
 -123.381222 44.530192
 -123.479913 44.625517
 -123.578917 44.720704
END
3595 -123.103772 45.009223
 -122.427717 45.101578
 -122.525757 45.198252
 -122.624122 45.294789
END
3676 -122.989567 44.147495
 -122.323040 44.238368
 -122.419523 44.335217
 -122.516322 44.431923
END
END

I'd like to read this file into R, but I'd like to retain only the indented lines.

This seems like a good job for grep, but I'm not sure how to make it work.

Any thoughts?

Upvotes: 2

Views: 97

Answers (1)

johannes
johannes

Reputation: 14433

You could try, where file.txt contains your data:

a <- readLines("file.txt")
a <- a[grepl("^ ", a)]
do.call("rbind", strsplit(a, " "))[, -1]
       [,1]          [,2]       
  [1,] "-123.381222" "44.530192"
  [2,] "-123.479913" "44.625517"
  [3,] "-123.578917" "44.720704"
  [4,] "-122.427717" "45.101578"
  [5,] "-122.525757" "45.198252"
  [6,] "-122.624122" "45.294789"
  [7,] "-122.323040" "44.238368"
  [8,] "-122.419523" "44.335217"
  [9,] "-122.516322" "44.431923"

# Alternatively you can get the data by read.table() as suggested by @Josh
read.table(textConnection(a))
         V1       V2
1 -123.3812 44.53019
2 -123.4799 44.62552
3 -123.5789 44.72070
4 -122.4277 45.10158
5 -122.5258 45.19825
6 -122.6241 45.29479
7 -122.3230 44.23837
8 -122.4195 44.33522
9 -122.5163 44.43192

Upvotes: 4

Related Questions