DD11
DD11

Reputation: 95

How to save output of for loop in a vector form

n <- as.numeric(n)
b <- c()
for (i in 2:(n-1))
{ 
  a <-   (n%%i) 
  if (a==0) {
   b <-  print(i)
  }

}

ouput

 n <- readline(prompt = "Enter the value of n:")
Enter the value of n:10

> n <- as.numeric(n)

> b <- c()

> for (i in 2:(n-1))
+ { 
+   a <-   (n%%i) 
+   if (a==0) {
+    b <-  print(i)
+   }
+   
+ }
[1] 2
[1] 5

I want my output in vector form. I am not sure what to do.I ve tried this one method I saw in other answers but couldnt succeed .

Upvotes: 0

Views: 118

Answers (2)

cbo
cbo

Reputation: 1763

EDIT : (the previous code didn't fully retake your question)

You can also (ab)use the fact that %% as most base function is Vectorized :

n <- 10
result <- n %% 2:(n-1)
# to get index
which(result == 0)
#> [1] 1 4
# to get numbers
(2:(n-1))[which(result == 0)]
#> [1] 2 5

Upvotes: 2

Federico Cattai
Federico Cattai

Reputation: 106

if you want to store results inside b vector, try this example:

n <- 10
b <- c()

for (i in 2:(n-1)){ 
  a <-   (n%%i) 
  if (a==0) {
    b <- c(b, i)
  }
}

Upvotes: 3

Related Questions