string 如何在R中重复字符串N次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22359127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to repeat a String N times in R?
提问by Marsellus Wallace
In Ruby I could repeat a String n times with the following:
在 Ruby 中,我可以使用以下内容重复字符串 n 次:
E.G. "my_string" * 2 -> "my_stringmy_string"
例如 "my_string" * 2 -> "my_stringmy_string"
Is there an equally simple way for doing this in R?
在 R 中是否有同样简单的方法来执行此操作?
回答by A5C1D2H2I1M1N2O1R2T1
You can use replicate
or rep
:
您可以使用replicate
或rep
:
replicate(2, "my_string")
# [1] "my_string" "my_string"
rep("my_string", 2)
# [1] "my_string" "my_string"
paste
will put it together:
paste
将它放在一起:
paste(replicate(2, "my_string"), collapse = "")
# [1] "my_stringmy_string"
回答by akrun
With R 3.3.0
, we can use strrep
from base R
有了R 3.3.0
,我们可以使用strrep
frombase R
strrep("my_string",2)
#[1] "my_stringmy_string"
We can also pass a vector of values in times
我们还可以在 times
strrep("my_string",1:3)
#[1] "my_string" "my_stringmy_string"
#[3] "my_stringmy_stringmy_string"
回答by bartektartanus
Use stri_dup
function from stringi
package
使用包中的stri_dup
函数stringi
stri_dup("abc",3)
[1] "abcabcabc"
It is also vectorized, so you can do this:
它也是矢量化的,所以你可以这样做:
> stri_dup(letters[1:3],4)
[1] "aaaa" "bbbb" "cccc"
Performance comparision :)
性能比较:)
> microbenchmark(stri_dup("abc",3),paste(replicate(3, "abc"), collapse = ""))
Unit: microseconds
expr min lq median uq max neval
stri_dup("abc", 3) 2.362 3.456 7.0030 7.853 64.071 100
paste(replicate(3, "abc"), collapse = "") 57.131 61.998 65.2165 68.017 200.626 100
> microbenchmark(stri_dup("abc",300),paste(replicate(300, "abc"), collapse = ""))
Unit: microseconds
expr min lq median uq max neval
stri_dup("abc", 300) 6.441 7.6995 10.2990 13.757 45.784 100
paste(replicate(300, "abc"), collapse = "") 390.137 419.7740 440.5345 460.042 573.975 100
回答by tmfmnk
The stringr
library offers the function str_dup()
:
该stringr
库提供以下功能str_dup()
:
str_dup("my_string", 2)
[1] "my_stringmy_string"
And it is vectorized over strings and times:
它在字符串和时间上被向量化:
str_dup(c("A", "B", "C"), 2:4)
[1] "AA" "BBB" "CCCC"