Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将数据追加到循环中的数据帧-函数仅返回数据帧的最后一行_R - Fatal编程技术网

R 将数据追加到循环中的数据帧-函数仅返回数据帧的最后一行

R 将数据追加到循环中的数据帧-函数仅返回数据帧的最后一行,r,R,我想创建一个函数,它循环遍历大量文件,计算每个文件的完整案例数,然后在现有数据框中添加一行,其中包含文件的“ID”编号及其相应的完整案例数 下面我创建了一个只返回数据帧最后一行的代码。我相信我的函数只返回最后一行,因为R在每个循环中都会覆盖我的数据帧,但我不确定。我在网上做了很多关于如何解决这个问题的研究,但是我找不到一个简单的解决方案(我对R非常陌生) 下面您可以看到我的代码和我得到的输出: complete <- function(directory = "specdata", id

我想创建一个函数,它循环遍历大量文件,计算每个文件的完整案例数,然后在现有数据框中添加一行,其中包含文件的“ID”编号及其相应的完整案例数

下面我创建了一个只返回数据帧最后一行的代码。我相信我的函数只返回最后一行,因为R在每个循环中都会覆盖我的数据帧,但我不确定。我在网上做了很多关于如何解决这个问题的研究,但是我找不到一个简单的解决方案(我对R非常陌生)

下面您可以看到我的代码和我得到的输出:

complete <- function(directory = "specdata", id = 1:332) {
  files_list <- list.files("specdata", full.names = T) # creates a list of files

  dat <- data.frame() # creates an emmpty data frame

    for (i in id) {

    data <- read.csv(files_list[i]) # reads the file "i" in the id vector 

    nobs <- sum(complete.cases(data)) # counts the number of complete cases in that file  

    data_frame <- data.frame("ID" = i, nobs) # here I want to store the number of complete cases in a data frame

    output <- rbind(dat, data_frame) # here the data_frame should be added to an existing data frame
  }

  print(output)
}

谢谢你的帮助!:)

而不是
for(i in id){
,尝试
for(i in 1:322){
for(i in 1:length(id){
在循环开始时

正如Maxim.K所说,有更好的方法可以做到这一点,但这里的实际问题是
输出
变量在
for
循环的每次迭代中都会被覆盖

尝试:


dat我将采用不同的方法:(1)编写一个函数,计算单个文件中完整案例的数量,(2)使用lappy()将该函数应用于文件列表,以及(3)使用do.call()与rbind()配合使用构建最终的数据帧。您可以在稍后阶段将所有三个步骤集成到单个函数中。如果没有可复制的示例,则编写相应的代码有点困难,因此我将此作为注释。
  ID nobs
1  5  402
dat <- rbind(dat, data_frame)