lundi 30 mars 2015

loop giving wrong output

I have an ex. to do. First I have to set wd, then create 100 files (i.txt). Each one of these files receives a random letter. Then I have to rename the files using the letters that were assigned to them (ex: 1.txt received letter C, thus it must be renamed as 1C.txt). I have then to create a new file (named "0.dat"), that appends the letters of each file. If they were appended as a character of length 1, I have to change to a character of length 100 and vice versa. However, the output of my code is wrong. If I do line by line it works, but when I run the entire code the answer is wrong. My code is:



# set wd

ROOT <- setwd("/Users/rebecadoctors/Documents/teste")

# confirm existance of dir, else create new

if (file.exists(paste(ROOT,"exercicio03", sep = "/"))){

stop("dir already exists")


} else{

dir.create(paste(ROOT,"exercicio03",sep="/"))
setwd("/Users/rebecadoctors/Documents/teste/exercicio03")

# create files (1:100)

for (i in 1:100){

# assign random LETTER to files

file.create(paste(i,"txt",sep="."))
AZ <- sample(LETTERS,1)
cat(AZ,file = paste0(ROOT,"/exercicio03/",i,".txt"))

# rename files, and create new file "ROOT/exericio03/0.dta" with append of LETTERS

name <- scan(file=paste0(ROOT,"/exercicio03/",paste(i,"txt",sep=".")),what = "character")
file.rename(paste0(ROOT,"/exercicio03/",paste(i,"txt",sep=".")), paste0(ROOT,"/exercicio03/",paste0(i),name,".txt"))
cat(name,file=paste0(ROOT,"/exercicio03/",0,".dat"),append = T)
NewFile <- scan(file=paste0(ROOT,"/exercicio03/",0,".dat"),what="character")
print(NewFile)

# if length(character)==1 change to length(character)==100

if (length(NewFile == 1)){

cat(name,file=paste0(ROOT,"/exercicio03/",1,".dat"),fill=T,append = T)
file.remove(paste0(ROOT,"/exercicio03/",0,".dat"))
file.rename(paste0(ROOT,"/exercicio03/",1,".dat"),paste0(ROOT,"/exercicio03/",0,".dat"))

}else {

#nothing

}
}

}


The output is :



[1] "R" "M"


when I was expecting to have:



[1] "F" "A" "R" "C" "C" "U" "S" "C" "A" "L" "Z" "Q" "G" "J" "T" "F" "A"
"B" "P" "P" "Z" "A" "W"
[24] "E" "R" "L" "I" "E" "L" "L" "Z" "U" "I" "N" "H" "O" "G" "Y" "D" "L"
"R" "P" "O" "A" "W" "N"
[47] "R" "F" "C" "C" "J" "V" "O" "M" "Z" "V" "D" "E" "K" "A" "U" "O" "G"
"V" "I" "Z" "G" "V" "A"
[70] "W" "A" "G" "L" "Q" "C" "I" "O" "R" "U" "D" "G" "J" "L" "B" "G" "N"
"N" "R" "F" "N" "G" "G"
[93] "U" "K" "G" "B" "V" "K" "P" "A"


Do you have any idea why it is happening? Thank you!


Aucun commentaire:

Enregistrer un commentaire