Kubazooo
Kubazooo

Reputation: 115

trouble with data processing in the loop

I have a loop that saves data to a file

wartosc_wierszy = dane_for*10
skok <- 2
for (i in 1:powtorzenia) {
    wynik_petli_P.P0.1 = wartosc_wierszy*i - wartosc_wierszy + skok 
    write.table(wynik_petli_P.P0.1,
        file="wynik_petli_P.P0.1.txt", append=TRUE, row.names=F, quote=FALSE, na=" ", col.names=FALSE)
}

wartosc_wierszy [1] 200

dane_for [1] 20

powtorzenia [1] 5

here is the results

 2
202
402
602
802
2
202
402
602
802
2
202
402
602
802

I would like the value to increase by +10 after each passing e.g

12
212
412
812

ect.

Upvotes: 2

Views: 40

Answers (2)

akrun
akrun

Reputation: 887311

This can be done in a vectorized way with seq and rep

seq(2, length.out = 5, by = 200) + rep(seq(0, 50, by = 10), each = 5)
#[1]   2 202 402 602 802  12 212 412 612 812  22 222 422 622 822  32 232 432 632
#[20] 832  42 242 442 642 842  52 252 452 652 852

Upvotes: 2

FKneip
FKneip

Reputation: 378

Can you not just add 10 in the for loop?

dane_for <- 20
wartosc_wierszy <- dane_for * 10
skok <- 2
powtorzenia <- 5
for (i in 1:powtorzenia) {
    wynik_petli_P.P0.1 <- wartosc_wierszy * i - wartosc_wierszy + skok + 10
    print(wynik_petli_P.P0.1)
    #write.table(wynik_petli_P.P0.1, file="wynik_petli_P.P0.1.txt",append=TRUE, row.names=F,quote=FALSE,na=" ",col.names=FALSE)
}
#[1] 12
#[1] 212
#[1] 412
#[1] 612
#[1] 812

Upvotes: 2

Related Questions