R中rep函数的使用

官方帮助文档如下写的:

Usage

rep(x, ...)

rep.int(x, times)

rep_len(x, length.out)

Arguments

x

a vector (of any mode including a list) or a factor or (for rep only) a POSIXct or POSIXlt or Date object; or an S4 object containing such an object.

...

further arguments to be passed to or from other methods. For the internal default method these can include:

times

A integer vector giving the (non-negative) number of times to repeat each element if of length length(x), or to repeat the whole vector if of length 1. Negative or NA values are an error.

length.out

non-negative integer. The desired length of the output vector. Other inputs will be coerced to an integer vector and the first element taken. Ignored if NA or invalid.

each

non-negative integer. Each element of x is repeated each times. Other inputs will be coerced to an integer vector and the first element taken. Treated as 1 if NA or invalid.

times

see ....

length.out

non-negative integer: the desired length of the output vector.

rep函数有4个参数:x向量或者类向量的对象,each:x元素每个重复次数,times:each后的向量的处理,如果times是单个值,则each后的值整体重复times次数,如果是x each后的向量相等长度的向量,则对each后的每个元素重复times同一位置的元素的次数,否则会报错;length.out指times处理后的向量最终输出的长度,如果长于生成的向量,则补齐。也就是说rep会先处理each参数,生成一个向量X1,然后times再对X1进行处理生成X2,length.out在对X2进行处理生成最终输出的向量X3。下面是示例:

> rep(1:4,times=c(1,2,3,4))  #与向量x等长times模式
[1] 1 2 2 3 3 3 4 4 4 4
> rep(1:4,times=c(1,2,3))  #非等长模式,出现错误
Error in rep(1:4, times = c(1, 2, 3)) : invalid 'times' argument
> rep(1:4,each=2,times=c(1,2,3,4)) #还是非等长模式,因为each后的向量有8位,而不是4位
Error in rep(1:4, each = 2, times = c(1, 2, 3, 4)) :
invalid 'times' argument
> rep(1:4,times=c(1,2,3,4))  #等长模式,我写重了o(╯□╰)o
[1] 1 2 2 3 3 3 4 4 4 4
> rep(1:4,times=c(1,2,3,4),each=3) #重复的例子啊,莫拍我
Error in rep(1:4, times = c(1, 2, 3, 4), each = 3) :
invalid 'times' argument
> rep(1:4,each=2,times=1:8)   #正确值,times8位长度向量
[1] 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
> rep(1:4,each=2,times=1:8,len=3)   #len的使用,循环补齐注意下
[1] 1 1 2
> rep(1:4,each=2,times=3)   #先each后times
[1] 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4
>rep函数完毕!

转载于:https://www.cnblogs.com/business-analysis/p/3414997.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值