不倒翁-R语言入门系列4-rep函数的用法
rep函数的官方简介:
我英语不是很好,英语好的大神自己去看官方英文说明,下面是我的简单翻译:
Rep会重复X中的值,这是一个一般的功能,下面是详细介绍。
rep.int and rep_len是更快的精简版,但是他们不是一般的用法。
使用方法:
rep(x, ...)
rep.int(x, times)
rep_len(x, length.out)
参数:
X可以是向量,列表,因子,或者日期格式(POSIXct or POSIXlt or Date object)
...:furtherarguments to be passed to or from other methods(应该是更高级的用法,这句没看懂)下面是内在设定的参数用法:
times:重复x的次数,不能是负数和NA,应该是正整数
length.out应该为非负整数,输出向量的期望长度,NA或者无效值将被忽略
each:非负整数,X的每个元素将会被重复each次,如果是NA或者无效值,将会被当做1.
细节:
在缺省情况下,rep函数相当于这样的设定:
rep(x, times = 1, length.out = NA, each = 1)
通常情况下,仅仅只有一个参数会被设定,
但是如果each和其他两个钟的一个或者两个一块别设定,那么会先运行each,然后在运行其他的参数。
如果times=n是一个单个的正整数,就会重复x,进行n次。如果x=c(x1,x2,……xn),times=c(n1,n2,……nn),那么就会重复x1n1次,x2n2次,……,xn,nn次。
Length.out可能会被用于代替times,如果两个参数都存在,则会先运行length.outNon-integer values oftimes will betruncated towards zero. Iftimes is a computedquantity it is prudent to add a small fuzz or use.And analogously foreach.
Ifx has lengthzero andlength.out is suppliedand is positive, the values are filled in using the extraction rules, that isby anNA of theappropriate class for an atomic vector (0 forraw vectors) andNULL for a list.
ValueAn object of the same type asx.
rep.int andrep_len returnno attributes (except the class if returning a factor).
The default method ofrep gives theresult names (which will almost always contain duplicates) ifx hadnames, but retains no other attributes.
NoteFunctionrep.int is a simplecase which was provided as a separate function partly for S compatibility and partlyfor speed (especially when names can be dropped). The performance ofrep hasbeen improved since, butrep.int is still atleast twice as fast whenx has names.
The namerep.int long precedesmakingrep generic.
Functionrep is aprimitive, but (partial) matching of argument names is performed as for normalfunctions.
For historical reasonsrep (only) worksonNULL: the result is alwaysNULL evenwhenlength.out is positive.
Although it has never been documented, these functions have alwaysworked on expression vectors.R 2.x.yaccepted pairlists and some other objects (although the results were rarelywhat their users intended).
ReferencesBecker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth &Brooks/Cole.
See Also,,.
Examplesrep(1:4, 2)rep(1:4, each = 2) # not the same.rep(1:4, c(2,2,2,2)) # same as second.rep(1:4, c(2,1,2,1))rep(1:4, each = 2, len = 4) # first 4 only.rep(1:4, each = 2, len = 10) # 8 integers plus two recycled 1's.rep(1:4, each = 2, times = 3) # length 24, 3 complete replicationsrep(1, 40*(1-.8)) # length 7 on most platformsrep(1, 40*(1-.8)+1e-7) # better## replicate a listfred
上面是具体用法,大家可以输入Rconsole,练习体会
另外例子中不太明白的是,
rep(1, 40*(1-.8)) # length 7 on most platforms
rep(1, 40*(1-.8)+1e-7) # better
请问大家有什么合理解释?
后面将会详细介绍sum()、max();min()
range(),mean(),median(),var(),sd(),sort(),rev(),rank(),append(),replace(),match(),pmatch(),
all(),any(),prod()等等,大约每周到每月更新一个吧。
第一个写的很烂,大家见谅。
如果有对量化投资或者翻译R语言中的相关函数感兴趣的,可以加入扣扣群: 226224941,大家相互合作,为了更好地学习R。