简体   繁体   English

R:重复 data.frame 的行 k 次并为新行值添加前缀

[英]R: Repeat rows of a data.frame k times and add prefix to new row values

I know from this answer how to duplicate rows of a dataframe. That's fine if you want to repeat the rows n times.我从这个答案中知道如何复制 dataframe 的行。如果你想重复这些行 n 次,那很好。

I want to do something similar but to also add a prefix within a column of newly added rows.我想做一些类似的事情,但还要在新添加的行的列中添加一个前缀。 Note: I am not basing the repetition count on the number of rows.注意:我没有将重复计数基于行数。 It needs to be provided by a parameter (call it k).它需要由参数(称为 k)提供。

So the operation should look like this assuming I want to repeat the dataframe k=3 times:因此,假设我想重复 dataframe k=3 次,操作应该如下所示:

Input:输入:

data.frame(a = c("1","2","3", "4"),b = c(1,2,3, 4))
  a b
1 "1" 1
2 "2" 2
3 "3" 3
4 "4" 4

Output: Output:

  a b
1 "1" 1
2 "2" 2
3 "3" 3
4 "4" 4
5 "1_1" 1
6 "1_2" 2
7 "1_3" 3
8 "1_4" 4
9 "2_1" 1
10 "2_2" 2
11 "2_3" 3
12 "2_4" 4

What's a nice R way to do this?? R 这样做的好方法是什么?

You could use expand_grid (assuming your data.frame is named df1 ):您可以使用expand_grid (假设您的 data.frame 被命名为df1 ):

library(dplyr)
library(tidyr)

expand_grid(a = df1$a, b = df1$b) %>% 
  mutate(a = paste(a, b, sep = "_")) %>% 
  bind_rows(df1, .)

This returns这返回

     a b
1    1 1
2    2 2
3    3 3
4  1_1 1
5  1_2 2
6  1_3 3
7  2_1 1
8  2_2 2
9  2_3 3
10 3_1 1
11 3_2 2
12 3_3 3

Using tidyverse with crossing使用带crossingtidyverse

library(tidyr)
library(dplyr)
 data.frame(a = c("1","2","3"),b = c(1,2,3)) %>%
   add_row(crossing(!!! .) %>%
   unite(a, a, b, remove = FALSE))

-output -输出

     a b
1    1 1
2    2 2
3    3 3
4  1_1 1
5  1_2 2
6  1_3 3
7  2_1 1
8  2_2 2
9  2_3 3
10 3_1 1
11 3_2 2
12 3_3 3

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

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