我对 R 编程和一般编程都很陌生。
这是我编写此脚本的目标:
我有 332 个 csv 文件。我想,“编写一个函数来读取充满文件的目录并报告每个数据文件中完全观察到的案例的数量。该函数应返回一个数据框,其中第一列是文件名称,第二列是完整案例数。”
-
函数概要如下:
完整
## '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
}
示例输出如下所示:
source("complete.R")
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
- 到目前为止我的脚本如下所示:
setwd("C:/users/beachlb/Desktop/R_Programming/specdata") #这是我的计算机上存储所有 332 个 csv 文件的本地目录
>complete <- function(directory, id = 1:332) {
>files_list <- list.files(directory, full.names=TRUE) #creates a list of files from within the specified directory
>dat <- data.frame() #creates an empty data frame that we can use to add data to
>for (i in id) {
>dat <- rbind(dat, read.csv(files_list[i])) #loops through the 332 csv files, rbinding them together into one data frame called dat
}
>dat$nobs <- sum(complete.cases(dat)) #add the column nobs to dat, populated with number of rows of complete cases in the dataframe
>dat_subset <- dat[which(dat[, "ID"] %in% id),] #subsets dat so that only the desired cases are included in output when function is run
>dat_subset[, "ID", "nobs"] #prints all rows of the desired data frame for the named columns}
当我按原样运行函数时,出现此错误:“drop && !has.j 中的错误:‘x && y’中的‘x’类型无效。我不确定是什么让我犯了这个错误。对于可能导致此错误的原因以及如何解决该错误的任何建议,我将不胜感激。向我指出我可以阅读的文献来研究这个问题和/或教程,这将帮助我加强避免此错误所需的编码技能,我也将不胜感激。
前言:我不确定是否应该在单独的线程中问这个问题。现在,我的函数被编写为填充所有行(所有 332 个文件)的完整案例总数,而不是专门计算给定监视器 ID 的完整案例数并将其仅放入该 ID 的列 nob 中。 (请注意,每个文件均以监视器 ID 命名,并且仅包含该监视器的案例,例如 001.csv = 监视器 1 的输出,002.csv = 监视器 2 的输出)。因此,我希望有人帮助我找到有关如何对数据进行子集化的资源,以便在填充 nobs 列时,nobs 列中的每一行给出每个 id 编号的完整案例数。
complete <- function(directory, id = 1:332) {
files_list <- list.files(directory, full.names=TRUE)
nobs <- c()
for (i in id) {
dat <- read.csv(files_list[i])
nobs <- c(nobs, sum(complete.cases(dat)))
}
data.frame(id,nobs)
}
你很接近。但您不应该一次读入所有文件,然后找到完整的案例。它不会为您按 id 分隔结果。相反,我只是稍微编辑了你的代码。
Test
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)