【发布时间】:2016-10-02 22:02:01
【问题描述】:
我尝试了几种方法来解决这个问题,但在编写它时遇到了麻烦。我想我前三个步骤是正确的,但现在我必须用来自y 的数字填充向量z,这些数字可以被四整除,不能被三整除,并且具有奇数位数。我知道我以错误的方式使用了print 函数,我只是不知道还能用什么......
这与其他问题不同,因为我没有使用 while 循环。
#Step 1: Generate 1,000,000 random, uniformly distributed numbers between 0
#and 1,000,000,000, and name as a vector x. With a seed of 1.
set.seed(1)
x=runif(1000000, min=0, max=1000000000)
#Step 2: Generate a rounded version of x with the name y
y=round(x,digits=0)
#Step 3: Empty vector named z
z=vector("numeric",length=0)
#Step 4: Create for loop that populates z vector with the numbers from y that are divisible by
#4, not divisible by 3, with an odd number of digits.
for(i in y) {
if(i%%4==0 && i%%3!=0 && nchar(i,type="chars",allowNA=FALSE,keepNA=NA)%%2!=0){
print(z,i)
}
}
【问题讨论】:
-
要打印连接的字符串,请使用
paste函数。例如,print(paste0(z, i)) -
对于这种类型的任务,您不需要(也不应该)使用循环(数据的直接子集应该可以工作,例如
y[y%%4 == 0 & y%%3 != 0 & nchar(y) %% 2 != 0]- 未经测试!) -
PS 你不需要指定所有可选参数:
nchar(i)应该可以正常工作 -
不客气。我觉得奇怪的是,在“R 简介”课程中,您学习了有关
for循环的内容,但由于子集通常更有效率且 r-way 做事,因此通常不鼓励使用它们
标签: r