本文介绍了用于R中的循环分配给数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 运行for循环之后,我无法分配数据帧。当我使用打印它给我的价值,任何解释吗? 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 for(i in new) + print(长度(独特(msales [(msales $ salesdate> =2013-12-23 msales $ salesdate> = i),] $ memberid))) [1] 500 [1] 400 [1] 300 [1] 200 [1] 100 test new for(i in new) + test [1:5]< -length(unique(msales [ msales $ salesdate> =2013-12-23| msales $ salesdate> = i),] $ memberid))>测试 [1] 100 100 100 100 100 我创建了一些示例。我的目标是统计当前日期的每个日期的唯一ID号码。感谢您的指导,大家。解决方案您正在将矢量化处理与索引混合。在第一个示例中,将(长度.....)中的一个数字分配给测试的所有元素,覆盖每个循环的数字。 类似于: test (新) $ b测试[i] =您的号码 会起作用。就像Paul提到的那样,代码不是很R-ish,但是既然你没有提供msales,我不能给你一个更好的例子。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 100I 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 numberwill 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. 这篇关于用于R中的循环分配给数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-25 15:42