datazang
datazang

Reputation: 1169

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". 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?

Upvotes: 2

Views: 2095

Answers (2)

www
www

Reputation: 39154

A base R solution. The idea is to prepare the row indices for the desired output. 1:nrow(data) is for all rows. which(data$type == "X") is for the rows you would like to duplicate. 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   

Upvotes: 1

SmokeyShakers
SmokeyShakers

Reputation: 3402

Filter and bind rows

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

Upvotes: 3

Related Questions