简体   繁体   English

如何 select 并在 r 中的 dataframe 中重复多行

[英]How to select and repeat a number of rows in a dataframe in r

I believe my question is quite simple, but I can't manage to find the right answer.我相信我的问题很简单,但我无法找到正确的答案。

In any given dataframe:在任何给定的 dataframe 中:

> data.frame(x0=c(1,2,3,4), x1=rnorm(4))
  x0         x1
1  1 -0.1868765
2  2 -0.2935534
3  3 -1.3934953
4  4  0.8165035

Imagine I'd like to take every two rows and repeat it by 2 times ending up with something like this:想象一下,我想每两行重复两次,结果是这样的:

> data.frame(x0=c(1,2,3,4), x1=rnorm(4))
  x0         x1
1  1 -0.1868765
2  2 -0.2935534
3  1 -0.1868765
4  2 -0.2935534
5  3 -1.3934953
6  4  0.8165035
7  3 -1.3934953
8  4  0.8165035


What is the easiest way to do this?最简单的方法是什么?

Thanks in advance!提前致谢!

You can create group of 2 rows and repeat it twice for each group, unlist the indices and subset.您可以创建 2 行组并为每个组重复两次,取消列出索引和子集。

set.seed(123)
df <- data.frame(x0=c(1,2,3,4), x1=rnorm(4))

inds <- seq(nrow(df))
df[unlist(tapply(inds, ceiling(inds/2), rep, 2)), ]

#    x0          x1
#1    1 -0.56047565
#2    2 -0.23017749
#1.1  1 -0.56047565
#2.1  2 -0.23017749
#3    3  1.55870831
#4    4  0.07050839
#3.1  3  1.55870831
#4.1  4  0.07050839

Actually, you could just do that using rep .实际上,您可以使用rep来做到这一点。

d[rep(seq(nrow(d)), each=2), ]
# x0          x1
# 1    1 -0.56047565
# 1.1  1 -0.56047565
# 2    2 -0.23017749
# 2.1  2 -0.23017749
# 3    3  1.55870831
# 3.1  3  1.55870831
# 4    4  0.07050839
# 4.1  4  0.07050839

Data:数据:

d <- structure(list(x0 = c(1, 2, 3, 4), x1 = c(-0.560475646552213, 
-0.23017748948328, 1.55870831414912, 0.070508391424576)), class = "data.frame", row.names = c(NA, 
-4L))

We can use uncount我们可以用uncount

library(dplyr)
library(tidyr)
df %>% 
   uncount(2) %>%
   as_tibble

-output -输出

# A tibble: 8 x 2
#     x0      x1
#  <dbl>   <dbl>
#1     1 -0.560 
#2     1 -0.560 
#3     2 -0.230 
#4     2 -0.230 
#5     3  1.56  
#6     3  1.56  
#7     4  0.0705
#8     4  0.0705

data数据

set.seed(123)
df <- data.frame(x0=c(1,2,3,4), x1=rnorm(4))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM