如果要跳过文件中的第一行和最后一行,可以按如下方式进行操作.用于readLines将文件读入字符向量,然后将其传递给read.csv.
strs <- readLines("filename.csv")
dat <- read.csv(text=strs, # read from an R object rather than a file
skip=1, # skip the first line
nrows=length(strs) - 3 # skip the last line
)
Run Code Online (Sandbox Code Playgroud)
这- 3是因为数据行数比文件中的文本行数少3:开头有1个跳过的行,列标题有1行,末尾有1个跳过的行.当然,您也可以忽略该nrows参数,并在导入后从数据框中删除无意义的行.
小智 5
您可以将注释放在数据文件中的任何位置,就像将注释放在R脚本中一样.例如,如果我有data.txt这样的:
# comment 1
str1
str2
# comment 2
str3
# comment 3
str4
str5# comment 4
str6
str7
# comment 5
Run Code Online (Sandbox Code Playgroud)
然后你不需要做任何事情来跳过评论:
> x<-read.table("data.txt", header=FALSE)
> x
V1
1 str1
2 str2
3 str3
4 str4
5 str5
6 str6
7 str7
>
Run Code Online (Sandbox Code Playgroud)
请注意,comment 4未读取.您可以#使用该comment.char选项更改注释字符.