加载后是否可以知道文件分隔符?
我需要让文件分隔符在 read.table 等选项中使用它。read.table(filename, encoding="UTF-8", stringsAsFactors=FALSE,header=TRUE, fill=TRUE,sep=XXXX(
很难说你在问什么,但听起来你试图在使用read.table
加载文件后找出原始文件分隔符。
不幸的是,答案是否定的。
但是你可以编写一个包装函数,在事后(尝试(捕获此信息:
read_table_capture_args <- function(...) {
# capture unevaluated arguments
outer_call <- match.call(expand.dots = FALSE)
dots <- outer_call$...
# pass those arguments to read.table() and save the result
inner_call <- as.call(c(as.name("read.table"), dots))
result <- eval(inner_call)
# update the captured arguments with the implied default arguments
all_args <- formals(read.table)
implicit_argnames <- setdiff(names(all_args), names(dots))
for (argname in implicit_argnames) {
inner_call[[argname]] <- all_args[[argname]]
}
# return the result with an attribute "call" that contains all of the
# arguments, explicit and implicit, used to produce the result
structure(result, call = inner_call)
}
然后,您可以使用它来恢复sep
参数,如下所示:
# load your data as usual
my_data <- read_table_capture_args(text = "x,y,zn1,2,3n4,5,6", header = TRUE, sep = ",")
# get the unevaluated call that was used to load your data
my_data_call <- attr(my_data, "call")
# get the value of sep that was passed
my_data_sep <- my_data_call$sep