我的任务是创建向量
0 1 0 1 0 1 0 1 0 1
在 R 中不使用or 的情况下使用两种方法。c()rep()
我尝试了很多方法,但似乎都不起作用。
以下是我的一些尝试(全部失败) -
vector(0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
a<-seq(from = 0, to = 1 , by = 1)
a
replicate(5, a)
b<-1*(0:1)
do.call(cbind, replicate(5, b, simplify=FALSE))
Run Code Online (Sandbox Code Playgroud)
任何对此的帮助将不胜感激!谢谢。
我们可以用bitwAnd
> bitwAnd(0:9, 1)
[1] 0 1 0 1 0 1 0 1 0 1
Run Code Online (Sandbox Code Playgroud)
或者kronecker
> kronecker(as.vector(matrix(1, 5)), 0:1)
[1] 0 1 0 1 0 1 0 1 0 1
> kronecker((1:5)^0, 0:1)
[1] 0 1 0 1 0 1 0 1 0 1
Run Code Online (Sandbox Code Playgroud)
或者outer
> as.vector(outer(0:1, (1:5)^0))
[1] 0 1 0 1 0 1 0 1 0 1
Run Code Online (Sandbox Code Playgroud)
my_rep()适用于您希望重复次数my_rep()的任何向量的通用解决方案xn
my_rep <- function(x, n) {
return(
# Use modulo '%%' to subscript the original vector (whose length I'll call "m"), by
# cycling 'n' times through its indices.
x[0:(length(x) * n - 1) %% length(x) + 1]
# 1 2 ... m 1 2 ... m 1 2 ... m
# | 1st cycle | | 2nd cycle | ... | nth cycle |
)
}
Run Code Online (Sandbox Code Playgroud)
可以解决这个问题
my_rep(x = 0:1, n = 5)
# [1] 0 1 0 1 0 1 0 1 0 1
Run Code Online (Sandbox Code Playgroud)
和许多其他人
# Getting cute, to make a vector of strings without using 'c()'.
str_vec <- strsplit("a b ", split = " ")[[1]]
str_vec
# [1] "a" "b" ""
my_rep(x = str_vec, n = 3)
# [1] "a" "b" "" "a" "b" "" "a" "b" ""
Run Code Online (Sandbox Code Playgroud)
另一种快速解决方案,适用于0 1 0 1 ... 0 1任意长度的向量l
# Whatever length you desire.
l <- 10
# Generate a vector of alternating 0s and 1s, of length 'l'.
(1:l - 1) %% 2
Run Code Online (Sandbox Code Playgroud)
产生输出:
[1] 0 1 0 1 0 1 0 1 0 1
Run Code Online (Sandbox Code Playgroud)
特别感谢@Adam ,在我对相同的解决方案发表评论后0:9 %% 2不久,他就自己想出了办法;他们优雅地收回了他们最初的回答,转而支持我的回答。:)