0

I am having trouble assigning to a dataframe after running the for loop. When I use print it give my value, any explanation to it?

 salesdate<-rep(seq(from=as.Date("2013-12-19"),to=as.Date("2013-12-23"),by=1),100)
 memberid<-as.factor(sample(1:1000,500))
 msales<-data.frame(salesdate,memberid)

 new<-seq(from=as.Date("2013-12-19"),to=as.Date("2013-12-23"),by=1)
 for(i in new) 
+   print(length(unique(msales[(msales$salesdate>="2013-12-23" | msales$salesdate>=i),]$memberid)))
[1] 500
[1] 400
[1] 300
[1] 200
[1] 100

 test <- rep(NA,length(new))
 new<-seq(from=as.Date("2013-12-19"),to=as.Date("2013-12-23"),by=1)
 for(i in new) 
+   test[1:5]<-length(unique(msales[(msales$salesdate>="2013-12-23" | msales$salesdate>=i),]$memberid))
> test
[1] 100 100 100 100 100

I created some sample. My goal is to count the number of unique id from each date period from current date. Thanks for the guide, guys.

chee.work.stuff
  • 326
  • 2
  • 14
  • Could you explain what you are trying to accomplish? There are often simpler alternatives than using a `for` loop. – Paul Hiemstra Feb 13 '14 at 09:49
  • 1
    Please also make your question [**reproducible**](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610), i.e. provide some dummy data - it makes it so much easier to help you. Cheers. – Henrik Feb 13 '14 at 09:54

1 Answers1

1

You are mixing vectorized processing with indexed. In the first example, you assign the one number from (length.....) to all elements of test, overwriting the numbers on each cycle. Only the last assignment is printed.

something like:

test = rep(NA,length(new))

for (i in new)
  test[i] = your number

will work. As Paul mentions, the code is not very R-ish, but since you did not provide msales, I cannot give you a better example.

Dieter Menne
  • 10,076
  • 44
  • 67