首页 > 解决方案 > 如何在R中一个一个地对文件进行采样而不进行替换

问题描述

我正在研究蒙特卡洛采样,我需要从文件夹中的文件列表中逐一进行采样。我不想添加任何重复的文件。因此,每个文件的名称都用作列名。所以我想避免有两个同名的列。我该怎么做?我必须有 100 个子样本,所以我不能分别对每个子样本进行采样。我的代码如下。

library(dplyr)
library(lubridate)
library(stringr)
library(raster)
library(rgdal)
library(readr)
library(sp)
library(rgeos)
library(mapdata)
library(sf)
library(data.table)

v<-c(1:500)
loop_N<-dataframe(v)    # dataframe 1 with which all the sampled dataframes will be joined
names(loop_N)<-c("Roads_ID")
loop_N$num_obs<-0
dir<-"Path"
fi <- list.files(dir, pattern="\\.csv$") #list of dataframes as shapefiles 
y1<-500
while(y1>=0){
  sample1 <- sample(fi, 1,replace = FALSE, prob=NULL) # i want each time sampling  with out replacement
  my_spdf<-read_csv(sample1)
  na<-sample1
  d<-substr(na, 1, 18)
  w<- str_replace_all(d,"_","-") # This is for the name of the column which shows me that if same file is sampled it will have the same column names
  addr<-data.frame(r$Row_Rd_No,r$value)    #sampled data frame
  names(addr)<-c("Road_ID",w)
  #dataframe added to loop_N by using Road_ID
  loop_N[, num_obs := Reduce(`+`, lapply(.SD,function(x) !is.na(x)))]
  loop_N<- subset(loop_N, num_obs != 7)
  y1=nrow(loop_N)
  y1<-as.numeric(y1)
  }

列名重复或对同一文件进行采样:我的输出。

预期输出如下

标签: rrandommontecarlo

解决方案


推荐阅读