2010-09-15 45 views
0

如何在R中获得输出作为向量?在循环中获得输出作为R中的向量

例如,如果我想有

for (i in 1:1000) {if i mod 123345 = 0, a = list(i)} 
a 

,但我想找到整除到123345(即因素)所有i,而不仅仅是规模最大的一次。

+0

另外,我会如何做同样的事情在VBA? – user446667 2010-09-15 19:55:24

回答

9

可能有这样做的更简洁的方式,但我会做这种方式:

i <- 1:1000 
j <- i[12345 %% i == 0 ] 

得到的载体j包含的值的矢量在我它们是12345因素就R modulo运算符是%%,在自己搜索时发现它有点麻烦。它隐藏在算术运算符的帮助文档中,您可以通过搜索+找到它,它必须用引号括起来,例如:?"+",然后你必须读一点。

如果您想查找VBA答案,最好添加一个VBA标签。但我怀疑这会涉及VBA模运算符;)

+0

啊,很好 - 谢谢 – user446667 2010-09-15 20:38:00

0

您写道:

for (i in 1:1000) {if i mod 123345 = 0, a = list(i)} a 

JD长的代码是好多了,但如果你想要这个糊涂的战略合作尝试,而不是:

a <- vector(mode="list"); for (i in 1:1000) {if (123345 %% i == 0){ a <-c(a,i) } } 
as.vector(unlist(a)) 
2

JD龙的方法实在是浮现在脑海的第一个,但另一个问题:

Filter(function(x) !(12345 %% x), 1:1000) 

余吨狡猾这是有趣的,以避免任何明确的任务的需要。 (在这种情况下,“!”将非零值转换为FALSE并将零值转换为TRUE。“过滤器”选出每个评估为TRUE的元素。)

还避免了单独配置的需要,而不是创建一个新的功能:

which(!(12345 %% 1:1000)) 

时间:

> y <- 1:1000 
> system.time(replicate(1e5, y[12345 %% y == 0 ])) 
    user system elapsed 
    8.486 0.058 8.589 
> system.time(replicate(1e5, Filter(function(x) !(12345 %% x), y))) 

Timing stopped at: 90.691 0.798 96.118 # I got impatient and killed it 
# Even pulling the definition of the predicate outside, 
# it's still too slow for me want to wait for it to finish. 
# I'm surprised Filter is so slow. 
> system.time(replicate(1e5, which(!12345 %% y))) 
    user system elapsed 
11.618 0.095 11.792 

所以,看起来像JD龙的方法就是赢家。

+0

在我的机器上,我得到了不同的时间,JD方法〜12.5s与你的方法〜11.5s。我正在使用R-2.11.1。 – Marek 2010-09-16 07:34:00

+0

奇怪;在我的笔记本电脑上,R-2.11.1 JD - 12.92s,David - 5.49s,但重复1000次。 – mbq 2010-09-16 09:10:06

+0

如果你想真正加速尝试将所有东西都转换为'integer':'system.time(replicate(1e5,y [12345L %% y == 0L]))''。 ('0L'的意思是'as.integer(0)') – Marek 2010-09-18 14:56:58