R:循环仅输出最后一次迭代 [英] R: Loop outputting only the last iteration

查看:128
本文介绍了R:循环仅输出最后一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文件夹中存储了39个json文件.它们都有三个共同的列: MOVEMENT_ID DISPLAY_NAME geometry .我想得到一个包含所有文件中的数据的数据集,这些数据被组织成这些列.我正在使用for循环来这样做.

I have 39 json files stored in a folder. They all have three columns in common: MOVEMENT_ID, DISPLAY_NAME and geometry. I would like to arrive at a dataset containing the data from all files, organised into these columns. I am using a for loop to do so.

path = "~/geoboundaries" #path to the folder where the files are stored
file.names=as.list(dir(path, pattern='.json', full.names=T)) 
#make a list of all file names
out.file=st_sf(MOVEMENT_ID=factor(), DISPLAY_NAME=factor(),
 geometry=st_sfc(), crs=st_crs(4326), sf_column_name='geometry') 
#define a void sf object in which the loop results will be stored

我想做一个循环,(1)读取文件列表中的每个文件;(2)仅保留 MOVEMENT_ID DISPLAY_NAME geometry 列;(3)将该文件添加到预定义的void sf对象中.

I want to make a loop that (1) reads each file in the file list; (2) keeps only MOVEMENT_ID, DISPLAY_NAME and geometry columns; (3) adds that file to the predefined void sf object.

for(i in 1:length(file.names))
 {
  file=st_read(file.names[i]) #(1)
  file=select(file, MOVEMENT_ID, DISPLAY_NAME, geometry) #(2)
  output=rbind(out.file, file) #(3) 
  }

使用此代码,输出仅包含最近读取的文件.

With this code, output contains only the last file that was read.

  • 无效的 sf 对象是否有问题?
  • 是否存在指定行的问题? output = rbind(out.file,file [i,])仅输出最后一个文件的一行.
  • Is this a problem with the void sf object?
  • Is it a question of specifying rows? output=rbind(out.file, file[i,]) outputs only one row of the last file.

推荐答案

我无法立即对其进行测试,但至少应根据您的情况为您提供解决方案.

I cannot test it right away but ths should at least point you to the solution in your case.

问题是您在每次迭代中都覆盖了 output ,因此在最后一次迭代之后只有最后一个可用.您尝试使用rbind做正确的事情,但是您必须再次使用以前创建的文件,并且基本上将输出附加到每次迭代中.

The problem is that you overwrite output in every iteration, so only the last one is available after the last iteration. You try to do the right thing by using rbind, but you have to use the formerly created file again and basically append the output within each iteration.

for(i in 1:length(file.names)) {
  file <- st_read(file.names[i]) #(1)
  file <- select(file, MOVEMENT_ID, DISPLAY_NAME, geometry) #(2)
  out.file <- rbind(out.file, file) #(3) 
}

最后一个不要:请使用箭头作为赋值运算符.R中的函数参数应使用等号.

A final not: please use arrows as assignment operators. The equal sign should be used for function arguments in R.

这篇关于R:循环仅输出最后一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆