R:循环仅输出最后一次迭代

编程入门 行业动态 更新时间:2024-10-24 14:16:10
本文介绍了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:循环仅输出最后一次迭代

本文发布于:2023-11-28 22:45:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!