1

I have an executable that outputs a table every time it is called by R. I then want to load the dataframe in R, but it contains lots of "!", for instance:

! A B C
  0 1 2
  3 3 2
  1 1 1
!
  3 4 2
  2 2 3
  5 2 5
!
  3 4 2
  .....

so that I get:

sim_stat <- read.table("C:/Users/Matteo/Desktop/Forest/Formind/formind-model/result/result.dia")
# Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
#  line 2 did not have 11 elements

I need to read the data in R every second more or less, so is there a fast way to remove those "!" ? I am working in Windows. Thanks!

Henrik
  • 65,555
  • 14
  • 143
  • 159
Matteo Fasiolo
  • 541
  • 6
  • 17

2 Answers2

4

You can have ! treated as a comment character:

read.table(file="...", comment.char="!")

That will get rid of the header, or any other lines with an extraneous !. If you have data in a line with !, and you want to ignore the ! but keep the rest, there is this long workaround:

> read.table(text=gsub("!", "", readChar("test.txt", file.info("test.txt")$size)), header=TRUE)
  A B C
1 0 1 2
2 3 3 2
3 1 1 1
4 3 4 2
5 2 2 3
6 5 2 5
7 3 4 2

Obviously replacing "test.txt" with your file name in both instances, and "!" with whatever character(s) to be ignored.

Señor O
  • 17,049
  • 2
  • 45
  • 47
  • That did, many thanks! In my case it commented out the first row, but that's fine. It would be nice to have a "ignore.char" option! – Matteo Fasiolo Jun 27 '14 at 18:00
  • @MatteoFasiolo Oh yeah it would take away your header! But that fix is easy as I'm sure you've figured out. `ignore.char` would be nice for this situation. – Señor O Jun 27 '14 at 18:07
  • Great! This "gsub" trick will certainly turn out to be useful. – Matteo Fasiolo Jun 27 '14 at 20:18
1

You can follow the same idea as in this answer, just remove the exclamation mark (or any other unwanted characters) instead of the commas.

Community
  • 1
  • 1
Greg Snow
  • 48,497
  • 6
  • 83
  • 110