r - 为什么 Demo 数据适用于我的 complete.R 函数,但来自测验的数据不适用?
问题描述
根据下面的要求,我写了一个函数complete.R
R Programming (Coursera) 的测验 2 中的要求:编写一个函数,该函数读取一个充满文件的目录并报告每个数据文件中完全观察到的案例的数量。该函数应返回一个数据框,其中第一列是文件名,第二列是完整案例的数量。
这是我的完整代码.R:
complete <- function(directory, id = 1:332) {
location <- paste(getwd(), directory, sep="/")
filenames <- list.files(location, full.names = TRUE)
dat <- data.frame()
for(i in id) {
data <- read.csv(filenames[i])
data <- na.omit(data)
df <- data.frame("id" = i, "nobs" = nrow(data))
dat <- rbind(dat, df)
}
dat
}
但是当我从测验中输入以下代码时:
set.seed(42)
cc <- complete("specdata", 332:1)
use <- sample(332, 10)
print(cc[use, "nobs"])
我的输出“87 96 576 76 237 4 121 117 361 932”甚至不是测验中的任何选项。正确的输出应该是“711 135 74 445 178 73 49 0 687 237”。
我尝试过跟踪演示数据,它们都可以工作。输出与演示结果相同。
complete("specdata", 1)
## id nobs
## 1 1 117
complete("specdata", c(2, 4, 8, 10, 12))
## id nobs
## 1 2 1041
## 2 4 474
## 3 8 192
## 4 10 148
## 5 12 96
complete("specdata", 30:25)
## id nobs
## 1 30 932
## 2 29 711
## 3 28 475
## 4 27 338
## 5 26 586
## 6 25 463
complete("specdata", 3)
## id nobs
## 1 3 243
所以我想不通。期待您的见解。谢谢你。
由于 R 版本,示例发生了变化。我使用 R3.6.0,而测验答案是在旧版本中生成的。以下是 Coursera 学习论坛的解决方案建议:
> vstr <- "3.5.1" ## This choice works, you do not
## need to have this version of R on your computer
> RNGversion(vstr) ## do this once in your R session
## before taking any quiz questions using the sample function
## This "tells" R to run the random number generators
## from that version of R
## It returns a warning saying that version of sample is
## not "best"
Warning message:
In RNGkind("Mersenne-Twister", "Inversion", "Rounding") :
non-uniform 'Rounding' sampler used
然后运行脚本并输入测验中的代码。
现在它起作用了!谢谢你。
解决方案
推荐阅读
- python - 拆分字符串,中间有 2 个空格
- matlab - 以下代码的矢量化有什么好处吗?
- regex - 自定义 grok 模式 - 匹配多个模式
- javascript - JavaScript Object Literal - 数据操作
- angular - Angular 7 项目的报告工具比较
- c++ - Boost TCP Server 未读取所有传入数据
- c# - ASP.NET MVC:尽管在 web.config 中设置了 maxRequestLength maxAllowedContentLength,但仍超出了最大请求长度
- .net - 在 OneDrive 之上构建一个 wrappr
- json - 在 PLJSON oracle 中解析字符串数组
- firebase - 在将文档添加到 Firestore 时,如何将其写入另一个名称不同的文档?