trilisser
trilisser

Reputation: 380

R: how to insert several rows by dplyr (add_row)

I have specific row numbers before which I want to paste new rows with some value (e.g., "lol"):

library(dplyr)
df <- data.frame(col1 = c("a","b","c","d"),
                 col2 = c("w","x","y","z"))
n <- c(1, 2, 4)

but an argument .before of the function add_row can only take one value:

add_row(df, col1 = "lol", col2 = "lol", .before = n)
  col1 col2
1  lol  lol
2    a    w
3    b    x
4    c    y
5    e    z

Is there the fastest way without loops, etc.?

Upvotes: 2

Views: 1163

Answers (1)

Ganesh Shastry
Ganesh Shastry

Reputation: 87

Updated the solution using lapply which is relatively faster than loop

  library(dplyr)
library(purrr)
df <- data.frame(col1 = c("a","b","c","d"),
                 col2 = c("w","x","y","z"))
n <- c(1, 2, 4)
lapply(n,FUN = function(x){df <<-add_row(df, col1 = "lol", col2 = "lol", .before = x)})
df

Upvotes: 1

Related Questions