简体   繁体   中英

For loop in R assigning to a data frame

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM