[R] select .txt from .txt in a directory

arun smartpink111 at yahoo.com
Fri Nov 8 21:18:03 CET 2013



Hi Atem,

It is not clear what you wanted to do.  If you want to transfer the subset of files from the main folder to a new location, then you may try: (make sure you create a copy of the original .txt folder before doing this)
I created three sub folders and two files (BTemperature_Stations.txt and Tempearture inventory.csv) in my working directory.


list.files()
#[1] "BTemperature_Stations.txt" "Files1"          ## Files1 folder contains all the .txt files; #SubsetFiles: created to subset the files that match the condition                 
#[3] "FilesCopy"                 "SubsetFiles1"          #FilesCopy. A copy of the Files1 folder   
#[5] "Tempearture inventory.csv"


 

list.files(pattern="\\.")
#[1] "BTemperature_Stations.txt" "Tempearture inventory.csv"
fl1 <- list.files(pattern="\\.")
 dat1 <- read.table(fl1[1],header=TRUE,sep="",stringsAsFactors=FALSE,fill=TRUE,check.names=FALSE)
 dat2 <- read.csv(fl1[2],header=TRUE,sep=",",stringsAsFactors=FALSE,check.names=FALSE)
vec1 <- dat1[,3][dat1[,3]%in% dat2[,3]]
vec2 <- list.files(path="/home/arunksa111/Zl/Files1",recursive=TRUE)
 sum(gsub(".txt","",vec2) %in% vec1)
#[1] 98
vec3 <-  vec2[gsub(".txt","",vec2) %in% vec1]
lapply(vec3, function(x) file.rename(paste("/home/arunksa111/Zl/Files1",x,sep="/"), paste("/home/arunksa111/Zl/SubsetFiles1",x,sep="/"))) #change the path accordingly. 
length(list.files(path="/home/arunksa111/Zl/SubsetFiles1"))
#[1] 98

fileDim <- sapply(vec3,function(x) {x1 <-read.delim(paste("/home/arunksa111/Zl/SubsetFiles1",x,sep="/"),header=TRUE,stringsAsFactors=FALSE,sep=",",check.names=FALSE); dim(x1)})
fileDim[,1:3]
#     dn3011120.txt dn3011240.txt dn3011887.txt
#[1,]          1151           791          1054
#[2,]             7             7             7


A.K.





On Friday, November 8, 2013 1:41 PM, Zilefac Elvis <zilefacelvis at yahoo.com> wrote:

Hi AK,


I want to select some files from a list of files. All are text files. The index for selection is found in column 3 of both files.


Attached are my data files.
Btemperature_Stations is my main file.
Temperature inventory is my 'wanted' file and is a subset of Btemperature_Stations.
Using column 3 in both files, select the files in Temperature inventory from Btemperature_Stations.
The .zip file contains the .txt files which you will extract to a folder and do the selection in R.

Thanks,
Atem.



More information about the R-help mailing list