0

I'm trying to manipulate a data frame in a loop, with R. This frame haves 100 observations with 3 variables.

#Lemmings in order
lemmings <- ds[order(ds$weights, ds$lifetimes),]

for(i in 100) {
 #Amount of Sightings on that specific moment
 s <- sum( lemmings[0:i,]$sightings )

 l <- s / lemmings$lifetimes
 w <- s / lemmings$weights

 #Change values; this will show warnings!
 lemmings$l[i] <- l
 lemmings$w[i] <- w

 print(l)
 print(w)
}
print(lemmings)

When I try to manipulate the frame, to add $l and $w I got this warning:

Warning messages:
1: In lemmings$l[i] <- l :
number of items to replace is not a multiple of replacement length
2: In lemmings$w[i] <- w :
number of items to replace is not a multiple of replacement length

The data values $l, $w are still the same as before (lifetimes, weights), see one row:

sightings   weights lifetimes        l           w
33.55230  0.579702         4   4.0000    0.579702

What can I do to remove the warnings messages, and to change the variables with my calculation?

Jeroen Steen
  • 531
  • 8
  • 22
  • 1
    If `i` only equals `100`, why a `for` loop? –  Oct 28 '15 at 10:16
  • 1
    In your code, `l` and `w` are vectors of length `i` (you can check this yourself). You're trying to assign them to one `cell` in the dataframe, which generates your error. However, looking at your code I think you don't need a loop after all, and could consider using `cumsum(lemmings$sightings)`. To add, R is 1- based. There is no 0-index. – Heroka Oct 28 '15 at 10:20
  • Because I want to use i to find s (look backwords into history for the sightings on that specific moment), is their a other way? – Jeroen Steen Oct 28 '15 at 10:23
  • 1
    Hard to say without a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example).... Can you make a small example of your data and the output you expect based on that input? (Like 5 rows). – Heroka Oct 28 '15 at 10:27
  • I think the cumulative sum function indeed will make it easier, instead of the loop, thanks Heroka – Jeroen Steen Oct 28 '15 at 10:33

1 Answers1

0

for(i in 100) {shouldnt it be for(i in 1:100) {

Marcin
  • 7,834
  • 8
  • 52
  • 99