Ran
Ran

Reputation: 11

try to create new variable using loop in R,but failed

I am a new user to R.I have already imported all data from all my txt file using the code down below,but i want to create a new variable when importing data,the variable is called case.The value of case for the first row is 1 and for the rest is 0.

And when i try to run the code,the console did not say anytime wrong ,the data has been imported, but the new variable wasn't created.I don't know why.

for(i in Filenames){
  perpos <- which(strsplit(i, "")[[1]]==".")
  data=assign(
    gsub(" ","",substr(i, 1, perpos-1)),
    read.table(paste(filepath,i,sep=""),fill=TRUE,header=TRUE,quote ="",row.names = NULL,sep="\t")
  )
  strsplit(i, "")
  filename  = strsplit(as.character(i),"\\.txt")
  data$case = ifelse(data$NAME=="filename",1,0)
} 

Upvotes: 0

Views: 117

Answers (2)

Ran
Ran

Reputation: 11

Thanks guys! I used @joosts's code and made some ajustment. The code down below works just fine.

fn <- paste(filepath,Filenames,sep="")
mylist <- lapply(fn, read.table,fill = TRUE, header = TRUE, quote = "",row.names = NULL, sep = "\t",stringsAsFactors=FALSE)
for(i in 1:length(Filenames)){
mylist[[i]]<- cbind(mylist[[i]], case = 0)
if(nrow(mylist[[i]])>0) {
mylist[[i]]$case[1] <- 1
}
mylist[[i]]<- cbind(mylist[[i]], ID = i)
}
do.call(rbind, mylist) 

Upvotes: 1

joosts
joosts

Reputation: 164

I am assuming you want to read in multiple text files, with each file containing the same columns (in the same order). In order to combine multiple dataframes (the things that result from calling read.data()), you should call the function rbind(). And I assume your code to get a filename without the extension is slightly overcomplex...

for(file in filenames) {
 sanitized_filename <- gsub(" ", "", strsplit(file, "\\.")[[1]][1])
 file.frame <- read.table(paste(filepath, file, sep=""), fill = TRUE, header = TRUE, quote = "", row.names = NULL, sep = "\t")
 file.frame <- cbind(file.frame, name = I(sanitized_filename), case = 0)
 if(nrow(file.frame)>0) {
   file.frame$case[1] <- 1
 }
 data <- ifelse(exists("data"), rbind(data, file.frame), file.frame)
}

Upvotes: 0

Related Questions