Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a problem with loop in R. I have written a simple program to load spectra, rewrite all data into a separate file, plot them and to mark position of a peaks. Unfortunately when I run the last loop, the outcome is very strange. All data points are beeing marked with cicrcles. When I run the commands from loop manually everything is OK.

Below is my code (I know it is a very "dirty" code, but I need to write a simple program that I understand to pass course, and I am a beginner with R) and the data I am working with.Files

Any help appreciated. Michal

#Podaj katalog, w którym są dane. Potem skopiuj, wklej i już 

csv_list=list.files(path=".", pattern="*.csv")              ##Wyszukuje pliki z rozszerzeniem ".csv"
csv_list <- csv_list[which(csv_list!="tabela.csv")]         ##Usuwa z listy plik "tabela.csv" (na wypadek ponownego uruchomienia programu w tym samym katalogu)
a=seq(along=csv_list)                                       ##Tworzy sekwencję o długości równej liczbie wczytanych plików
b=seq(along=csv_list)
files=max(a)                                                ##Liczba wczytywanych plików (pomoc do tworzenia tabeli)
file_names=sub(pattern=".csv",replacement="",x=csv_list)    ##Usuwa rozszerzenia z nazw plików

##tworzy tabele na wyniki i wyniki bez szumu

tabela=matrix(ncol=files+1,data=rep(1:1867,each=(files+1))) 
no_noise=matrix(ncol=files+1,data=rep(1:1867,each=(files+1)))

##zbiera wyniki z plików w jedną tabelę, szuka wartości minimalnych i maksymalnych (do wykresu):

for (i in 1:files) {spectra=read.table(csv_list[i],header=FALSE,sep=",",dec=".",skip=1,nrows=1868) 
        tabela[,1]=spectra$V1
        tabela[,i+1]=spectra$V2
        a[i]=max(spectra$V2)
        b[i]=min(spectra$V2)}

        ##odszumia dane poniżej 10*mediana
for (i in 1:files) {spectra=read.table(csv_list[i],header=FALSE,sep=",",dec=".",skip=1,nrows=1868) 
        no_noise[,1]=spectra$V1
        no_noise[,i+1]=spectra$V2}

        for (i in 1:files+1){ no_noise[,c(i)][no_noise[,c(i)]< 10*median(tabela[,c(i)])] <- 0}
        df=as.data.frame(no_noise)
        rm(no_noise)


##zapisuje tabelkę z liczbami w pliku .csv, separator kolumn to ",", nagłowki kolumn to nazwy plików

write(c("wawelength",csv_list),file="tabela.csv",ncolumns=files+1, append=TRUE, sep=",")
write.table(tabela,file="tabela.csv",append=FALSE,quote=TRUE, sep=",",row.names=FALSE,col.names=FALSE)                      


##rysuje osie i dopasowuje skalę do wyników; dopasowanie skali -wartości w nawiasie przy xlim, ylim; funkcja kasuje poprzedni wykres

plot(x=0,y=0,xlim=c(min(tabela[,1]),max(tabela[,1])),ylim=c(min(b),max(a)),xlab=expression(paste("Raman shift /", cm^-1, "", sep = "")),ylab='Absorbance')                          


##rysuje wykresy z tej tabeli z danymi w różnych kolorach z legendą

for (i in 1:files) lines(x=tabela[,1],y=tabela[,i+1],type="l",lwd=0.5,col=i)
legend("topright",legend=file_names,lwd=0.5,col=c(1:files))

##Funkcje szukające maksimów
peaks <- function(series, span = 3, do.pad = TRUE) {
if((span <- as.integer(span)) %% 2 != 1) stop("'span' must be odd")
s1 <- 1:1 + (s <- span %/% 2)
if(span == 1) return(rep.int(TRUE, length(series)))
z <- embed(series, span)
v <- apply(z[,s1] > z[, -s1, drop=FALSE], 1, all)
if(do.pad) {
    pad <- rep.int(FALSE, s)
    c(pad, v, pad)
} else v
}


##Wyszukanie maksimów w zaimportowanych plikach
m=as.matrix(df)

for (i in 2:files+1)    {
    d.peaks <- peaks(m[,c(i)], 5)
    peak_idx <- which(d.peaks)
    points(m[,c(i)] ~ m[,c(1)], data=m[peak_idx, ], col = i-1, cex = 1.5)
    }
rm(m)

dev.copy(png,'graph.png')
dev.off()
share|improve this question
1  
I don't have time to go through your code, but are you sure you want to loop over i in 2:files+1 and not i in 2:(files+1)? –  Roland May 15 '13 at 7:42
    
You're right, I want to loop over i in 2:(files+1), but it is bot the problem. idk why last loop is messing everything :( –  zenon21 May 15 '13 at 7:51
    
The default plotting character for points is a hollow circle, have you tried setting the pch parameter? –  James May 15 '13 at 9:59
    
I have found solution. for (i in 2:(files+1)) { d.peaks <- peaks(df[,i], 5) peak_idx <- which(d.peaks) points(x=df$V1[peak_idx],y=df[,i][peak_idx],col = i-1, cex = 1.5)} –  zenon21 May 15 '13 at 10:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.