Reputation: 121
I am running the following lines of code and facing the above-mentioned error. Any ideas how to fix this ?
X <- NULL
S <- NULL
remove.value <- NULL
N <- seq.int(1, 25)
repeat {
S <- sample(N, 1, replace = FALSE, prob = NULL)
S
if (S == 1) {
remove.value <- c(S, S + 1)
} else if (S == 25) {
remove.value <- c(S, S - 1)
} else {
remove.value <- c(S - 1, S, S + 1)
}
remove.value
N <- N [which(!(N %in% remove.value))]
N
if (is.null(N)) break
}
Upvotes: 5
Views: 37837
Reputation: 1463
I'm also struggling with this in an entirely different setting. I think the answer of @DatamineR is correct. You can see this by trying:
sample(NULL, 1)
sample(integer(0), 1)
where you get the same error message:
Error in sample.int(length(x), size, replace, prob) :
invalid first argument
I still find this very misleading because neither of us called sample.int() ;) Doesn't make debugging easier. But for me at least that was the issue, we actually tried to sample from nothing.
Upvotes: 0
Reputation: 11
Removing the library Tidyverse
solved this issue for me. The problem seems to be RStudio calling the sample.int()
instead of simply sample()
. Cheers!
Upvotes: 1
Reputation: 9618
It actually works as you intend. You can see it if you insert print(N)
> repeat{
S<-sample(N ,1, replace = FALSE, prob = NULL)
S
if (S==1) {
remove.value<-c(S,S+1)
} else if (S==25) {
remove.value<-c(S,S-1)
}else {remove.value<-c(S-1,S,S+1)
}
remove.value
N <- N [which(N %!in% remove.value)]
print(N)
if (is.null(N)) break
}
[1] 1 2 3 4 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
[1] 1 2 3 4 8 9 10 11 12 13 14 15 16 17 18 19 20 21 25
[1] 1 2 3 4 8 9 13 14 15 16 17 18 19 20 21 25
[1] 1 2 3 4 8 9 13 14 15 16 17 18 25
[1] 1 2 3 4 8 9 16 17 18 25
[1] 1 2 3 4 8 9 25
[1] 1 2 8 9 25
[1] 8 9 25
[1] 8 9
integer(0)
Error in sample.int(length(x), size, replace, prob) :
invalid first argument
The error is caused by the final value of N
, which is integer(0)
, and not NULL
. If you use if (length(N)== 0) break
instead of if (is.null(N)) break
the code works without error message.
Upvotes: 5