How to do double "for loop" (first for files, second for datas in files) in R -
i've started r, i'm self-taught person , have problem loop. looking answers can't find anything.
i've got lot of files different names , i've got lot datas in 1 file. made loop 1 file , works - it's (but has more calculations):
12bielawica9.txt looks like
na na na 0.002 0.002 na na na na na na na na na na na na na na na na na 0.008 0.006 na na na na na na na na na na na na na na
but it's more bigger
it contains results of researches, that's why there's lot of nas. looks different reasearches....(there's less nas) wrote in r
dane = dane = read.table("12bielawica9.txt", header=t) (i in dane) { x = sd(i, na.rm=t) y = length (na.omit(i)) if (y == 0) { cat(file="12bielawica9.txt", append=t, (paste("-","\t"))) } else if (x == "0") { cat(file="12bielawica9.txt", append=t, paste(format(mean(i, na.rm=t) - mean(i, na.rm=t), digits=5), "\t")) } else { cat(file="12bielawica9.txt", append=t, paste(format(t.test(na.omit(i), conf.level=0.90)$conf.int - mean(i, na.rm=t), digits=5), "\t")) } }
first of i'd create loop files, when made loop like:
myfiles <- list.files(pattern=".*txt") (j in 1:length(myfiles)) { (i in myfiles[j]) { #loop above } }
and now, list.files returns every file (like 12bielawica.txt), on need make calculations. clear?
r return 1 result every file (like conjuction). i'd achieve result matrixes every file (like first loop ). don't know how write new file automaticaly...
i hope understand mean. don't strict me, please.
you're close. in question, thing right before first (inner) loop read in file.
dane = read.table("12bielawica9.txt", header=t)
and loop refers (for (i in dane)
). still need read stuff when wrap in outer loop:
myfiles <- list.files(pattern=".*txt") (j in 1:length(myfiles)) { this_file <- read.table(myfiles[j], header = t) (i in this_file) { #loop above } }
should make loop work.
you want store output in matrix or something. should initialize empty matrix store results, , have inner loop insert results. like
results_mat <- matrix(na, nrow = 2, ncol = length(myfiles)) ## 1st row x, second row y, 1 column per file
then change inner loop
for (i in dane) { x = sd(i, na.rm=t) y = length (na.omit(i)) results_mat[, j] <- c(x, y) }
you can, of course, expand more rows of results... i'll leave you. can colnames(results_mat) <- myfiles
can tell results correspond files.
Comments
Post a Comment