在R中重复矢量元素

时间:2020-12-13 09:17:12

I'm trying to repeat the elements of vector a, b number of times. That is, a="abc" should be "aabbcc" if y = 2.

我试图重复矢量a,b的元素次数。也就是说,如果y = 2,则a =“abc”应为“aabbcc”。

Why doesn't either of the following code examples work?

为什么以下任何一个代码示例都不起作用?

sapply(a, function (x) rep(x,b))

and from the plyr package,

从plyr包装,

aaply(a, function (x) rep(x,b))

I know I'm missing something very obvious ...

我知道我错过了一些非常明显的东西......

2 个解决方案

#1


10  

Assuming you a is a vector, sapply will create a matrix that just needs to be collapsed back into a vector:

假设你是一个向量,sapply会创建一个只需要折叠回向量的矩阵:

a<-c("a","b","c")
b<-3 # Or some other number
a<-sapply(a, function (x) rep(x,b))
a<-as.vector(a)

Should create the following output:

应该创建以下输出:

"a" "a" "a" "b" "b" "b" "c" "c" "c"

#2


16  

a is not a vector, you have to split the string into single characters, e.g.

a不是矢量,你必须将字符串拆分成单个字符,例如

R> paste(rep(strsplit("abc","")[[1]], each=2), collapse="")
[1] "aabbcc"

#1


10  

Assuming you a is a vector, sapply will create a matrix that just needs to be collapsed back into a vector:

假设你是一个向量,sapply会创建一个只需要折叠回向量的矩阵:

a<-c("a","b","c")
b<-3 # Or some other number
a<-sapply(a, function (x) rep(x,b))
a<-as.vector(a)

Should create the following output:

应该创建以下输出:

"a" "a" "a" "b" "b" "b" "c" "c" "c"

#2


16  

a is not a vector, you have to split the string into single characters, e.g.

a不是矢量,你必须将字符串拆分成单个字符,例如

R> paste(rep(strsplit("abc","")[[1]], each=2), collapse="")
[1] "aabbcc"