这是一个非常基本的问题,但这让我烦恼,所以我在问。
我需要一系列重复的数字,即1 1 ... 1 2 2 ... 2 3 3 ... 3等我实现这个的方式是
nyear<-20
names<-c(rep(1,nyear),rep(2,nyear),rep(3,nyear),rep(4,nyear),
rep(5,nyear),rep(6,nyear),rep(7,nyear),rep(8,nyear))
哪个有效,但很笨拙,显然不能很好地扩展。如何按顺序重复N次整数M次?我尝试嵌套seq()和rep(),但这并不是我想要的。我显然可以写一个for循环来做这件事,但这看起来也很笨拙 - 应该有一种内在的方法来做到这一点!
答案 0 :(得分:129)
您错过了each=
的{{1}}参数:
rep()
所以你的例子可以用简单的
完成R> n <- 3
R> rep(1:5, each=n)
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R>
答案 1 :(得分:1)
另一个#Iterate over paragraphs
for paragraph in document.paragraphs:
#Perform the below logic only for paragraph content which does not have it's native style as "Heading"
if "Heading" not in paragraph.style.name:
#Start of by initializing an empty string to store bold words inside a run
runboldtext = ''
# Iterate over all runs of the current paragraph and collect all the words which are bold into the varible "runboldtext"
for run in paragraph.text:
if run.bold:
runboldtext = runboldtext + run.text
# Now check if the value of "runboldtext" matches the entire paragraph text. If it matches, it means all the words in the current paragraph are bold and can be considered as a heading
if runboldtext == str(paragraph.text) and runboldtext != '':
print("Heading True for the paragraph: ",runboldtext)
style_of_current_paragraph = 'Heading'
选项可以是base R
:
gl()
其中输出是一个因素:
gl(5, 3)
如果需要整数,则可以将其转换:
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5
答案 2 :(得分:0)
对于您的示例,德克的答案是完美的。如果您有一个数据框,并想将这种序列添加为一列,则还可以使用groupdata2中的group
(免责声明:我的包)将这些数据点贪婪地分成几组。
# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
x .groups
<dbl> <fct>
1 0.891 1
2 -1.13 1
3 -0.500 1
4 -1.12 1
5 -0.0187 1
6 0.420 2
7 -0.449 2
8 0.365 2
9 0.526 2
10 0.466 2
# … with 17 more rows
有各种各样的方法可以创建这种分组因子。例如。按组数,组大小列表,或通过在某列中的值与上一行中的值不同时(例如,如果某列为c("x","x","y","z","z")
,则分组因子为{{1})来使组开始}。