gpt4 book ai didi

r - 为什么 expand.grid 忽略选项?

转载 作者:行者123 更新时间:2023-12-04 00:09:45 25 4
gpt4 key购买 nike

我遇到了 expand.grid 的问题.它似乎忽略了我在脚本顶部设置的选项。

例如:

options(stringsAsFactors = FALSE)
tmp <- expand.grid(x = letters, y = 1:10)

返回:
> str(tmp)
'data.frame': 260 obs. of 2 variables:
$ x: Factor w/ 26 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ...
$ y: int 1 1 1 1 1 1 1 1 1 1 ...
- attr(*, "out.attrs")=List of 2
..$ dim : Named int 26 10
.. ..- attr(*, "names")= chr "x" "y"
..$ dimnames:List of 2
.. ..$ x: chr "x=a" "x=b" "x=c" "x=d" ...
.. ..$ y: chr "y= 1" "y= 2" "y= 3" "y= 4" ...

我做错了什么?

最佳答案

这是因为 expand.grid的函数参数默认设置为 TRUE .如果您只输入 ?expand.gridhead(expand.grid)从 R session 中,您将看到函数定义为:

> head(expand.grid)

1 function (..., KEEP.OUT.ATTRS = TRUE, stringsAsFactors = TRUE)
2 {
3 nargs <- length(args <- list(...))
4 if (!nargs)
5 return(as.data.frame(list()))
6 if (nargs == 1L && is.list(a1 <- args[[1L]]))

这与提供给 read.table() 的默认值不同。 ,例如:
> head(read.table)
1 function (file, header = FALSE, sep = "", quote = "\\"'", dec = ".",
2 row.names, col.names, as.is = !stringsAsFactors, na.strings = "NA",
3 colClasses = NA, nrows = -1, skip = 0, check.names = TRUE,
4 fill = !blank.lines.skip, strip.white = FALSE, blank.lines.skip = TRUE,
5 comment.char = "#", allowEscapes = FALSE, flush = FALSE,
6 stringsAsFactors = default.stringsAsFactors(), fileEncoding = "",

哪里 default.stringsAsFactors()基本会返回 getOption("stringsAsFactors") .

因此,您必须明确设置它。

关于r - 为什么 expand.grid 忽略选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24048390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com