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
  • Please do not repost; this was already asked and answered yesterday: http://stackoverflow.com/questions/21750123/for-loop-in-r-assigning-to-a-data-frame/21750630#21750630 – Dieter Menne Feb 14 '14 at 07:58

1 Answers1

2

I'm not 100% sure what you're trying to do, but I the main problem is you are assigning to [1:5] at every loop iteration, which means that by the end you'll have the final value (100) assigned to all five because in the final iteration (and every other one) you will assign to all five spots ([1:5]). Here is an alternative:

test <- rep(NA,length(new))
for(i in seq_along(new)) 
  test[i]<-length(
    unique(
      msales[(msales$salesdate>="2013-12-23" | msales$salesdate>=new[[i]]),]$memberid
  ) )  
test

The key part is test[i] <- .... This produces:

# [1] 500 400 300 200 100`

Notice also how in the condition we need to use msales$salesdate >= new[[i]]

BrodieG
  • 51,669
  • 9
  • 93
  • 146