简体   繁体   English

根据 R 中的条件复制行

[英]Copy rows based on the condition in R

I have a data set as I've shown below:我有一个数据集,如下所示:

data <- tribble(
~book_name,  ~clicks,  ~type,
  "A",         10,       "X",
  "B",         20,       "Y",
  "C",         30,       "Y",
  "A",         10,       "Z",
  "A",         10,       "X",
)

Now, I want to copy and paste the rows if the type is "X".现在,如果类型为“X”,我想复制并粘贴行。 So, my desired data set is something like this:所以,我想要的数据集是这样的:

desired_data <- tribble(
  ~book_name,  ~clicks,  ~type,
  "A",         10,       "X",
  "B",         20,       "Y",
  "C",         30,       "Y",
  "A",         10,       "Z",
  "A",         10,       "X",
  "A",         10,       "X",
  "A",         10,       "X",
)

How to do this?这该怎么做?

Filter and bind rows过滤和绑定行

data_x <- data %>% filter(type == 'X')
desired_data <- bind_rows(data,data_x)

A base R solution.基本的 R 解决方案。 The idea is to prepare the row indices for the desired output.这个想法是为所需的输出准备行索引。 1:nrow(data) is for all rows. 1:nrow(data)适用于所有行。 which(data$type == "X") is for the rows you would like to duplicate. which(data$type == "X")用于您要复制的行。 By combing these two parts together, we can get the desired output.通过将这两部分组合在一起,我们可以获得所需的输出。

data[c(1:nrow(data), which(data$type == "X")), ]
# # A tibble: 7 x 3
#   book_name clicks type 
#   <chr>      <dbl> <chr>
# 1 A             10 X    
# 2 B             20 Y    
# 3 C             30 Y    
# 4 A             10 Z    
# 5 A             10 X    
# 6 A             10 X    
# 7 A             10 X   

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

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