简体   繁体   English

在R中加载包含无用字符的数据框

[英]Loading dataframe containing useless characters in R

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: 我有一个可执行文件,每次被R调用时都会输出一个表。然后,我想将数据帧加载到R中,但是它包含很多“!”,例如:

! 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 "!" 我需要或多或少每秒读取R中的数据,所以有一种快速的方法来删除那些“!” ? I am working in Windows. 我正在Windows中工作。 Thanks! 谢谢!

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 "!" 显然在两个实例中都用文件名替换了“ test.txt”,“!” with whatever character(s) to be ignored. 与任何要忽略的字符。

您可以遵循与该答案相同的想法,只需删除感叹号(或任何其他不需要的字符)而不是逗号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM