-1

I have multiple data frames with the exact same structure. I'd like to loop through all these data frames and remove rows where the variable "Hat" = D. Below is what I have for a singular instance but would like to write a loop to do this for multiple data frames.

final_prices_designations_20161101_20161114.csv <- subset.data.frame(final_prices_designations_20161101_20161114.csv, 
    final_prices_designations_20161101_20161114.csv$Hat == "D")
MrFlick
  • 195,160
  • 17
  • 277
  • 295
Nathan
  • 1
  • 1
  • 2
    If you have a bunch of related data.frames that you want to perform similar operations on, chances are they should have been in a list rather than a bunch of separate variables. See [how to make a list of data.frames](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for ideas on how to better structure your data so make operations like this easier. – MrFlick Dec 08 '17 at 15:14

2 Answers2

0

The easiest way to manage this is to use an apply() function to read the data and subset items to remove where Hat == 'D'.

# first, read list of files from disk 
theCSVFiles <- list.files(...)  
# read each file and subset to eliminate Hat == D 
fileList <- lapply(theCSVFiles,function(x) read.csv(x)[x$Hat!='D',])
# if necessary to combine to single file
aResult <- do.call(rbind,fileList) 
Len Greski
  • 10,505
  • 2
  • 22
  • 33
0
#Install the library 'zonator' for function 'file_path_sans_ext'
install.packages("zonator")
library(zonator)
#Change filesPath with location for your data
filesPath <- "D:/R/Import files/"
#file_path_sans_ext : to read files without extension
files <- file_path_sans_ext(list.files(filesPath))
#loop : I chose a loop to create a physicals tables
for (i in 1:length(files)){
  tempTable=read.csv(paste0(filesPath,files[1],".csv"),sep=';')
  assign(files[i] ,tempTable[tempTable$Hat!='D',])
}
remove(tempTable)# to delete temporary table
YouKH
  • 21
  • 1
  • It is better to make a list of dataframes: `L <- lapply(paste0(filesPath,files,".csv"), ...)` – jogo Dec 09 '17 at 13:14
  • Ok. I changed the loop by : L <- lapply(files, function(x) { tempTable <- read.csv(paste0(filesPath,x,".csv"),sep=';') tempTable[tempTable$Hat!='D',] }) – YouKH Dec 09 '17 at 15:25