【发布时间】:2017-02-20 14:16:18
【问题描述】:
我正在做以下工作。该功能仅在传递一个 ID 时起作用。但是,如果传递了多个 ID(例如 c(2,4,6) 或 2:6),则输出不正确。
编写一个函数,读取一个满是文件的目录,并报告每个数据文件中完全观察到的病例数。该函数应返回一个数据框,其中第一列是文件名,第二列是完整案例的数量。这是我的代码,虽然它在仅传递一个 ID 时有效,但在传递更多 ID 或一系列 ID 时似乎无法获得正确的输出。这是一个原型:
complete <- function(directory, id = 1:332) {
## 'directory' is a character of length 1
## indicating the location of the CSV file
## 'id' is an integer vector
## indicating the monitor ID numbers to be used
## Return a data frame of the form:
## id nobs
## 1 117
## 2 1041
## ...
## where 'id' is the monitor ID number and
## 'nobs' is the number of complete cases
}
这是我的代码:
complete <- function(directory, id = 1:332) {
#lists the files in the directory
files_full <- list.files(directory, full.names = TRUE)
#empty data frame were we will store the read from the loop
dat <- data.frame()
nobs = numeric()
for (i in id) {
## binds all the rows of the of the files with "specified" ID
dat <- rbind(dat, read.csv(files_full[i]))
nobs <- sum(complete.cases(dat))
}
returnVal <- data.frame(id, nobs)
returnVal
}
这些是输出:
complete("specdata", 1)
id nobs
1 1 117
complete("specdata", c(2, 4, 8, 10, 12))
id nobs
1 2 1951
2 4 1951
3 8 1951
4 10 1951
5 12 1951
谁能告诉我我做错了什么?
【问题讨论】: