Home > Net >  How to slice n rows and append these at the end of dataframe by given n in a column
How to slice n rows and append these at the end of dataframe by given n in a column

Time:12-29

I have this dataframe:

structure(list(id = 1:5, mpg = c(21, 21, 22.8, 21.4, 18.7), cyl = c(6, 
6, 4, 6, 8), n = c(2, 2, 2, 2, 2)), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame"))

     id   mpg   cyl     n
  <int> <dbl> <dbl> <dbl>
1     1  21       6     2
2     2  21       6     2
3     3  22.8     4     2
4     4  21.4     6     2
5     5  18.7     8     2

I want to slice row 1:n, where n is given in a column (here: 2), and

then I want to append these rows at the end of the dataframe.

Desired output:

id   mpg   cyl     n
<int> <dbl> <dbl> <dbl>
1  21       6     2
2  21       6     2
3  22.8     4     2
4  21.4     6     2
5  18.7     8     2
1  21       6     2
2  21       6     2

I have tried so far: (appends only one row!)

library(dplyr)
df %>% 
  bind_rows(df[1:unique(n),]) 

     id   mpg   cyl     n
  <int> <dbl> <dbl> <dbl>
1     1  21       6     2
2     2  21       6     2
3     3  22.8     4     2
4     4  21.4     6     2
5     5  18.7     8     2
6     1  21       6     2
Warning message:
In 1:unique(n) : numerical expression has 15 elements: only the first used

I want to learn how to put unique(n) in this part df[1:unique(n),].

CodePudding user response:

If we want to use bind_rows with slice - get the first value of 'n' convert to sequence (seq_len) and slice, then bind the data with the original data

library(dplyr)
df %>% 
    slice(seq_len(first(n))) %>%
    bind_rows(df, .)

-output

# A tibble: 7 × 4
     id   mpg   cyl     n
  <int> <dbl> <dbl> <dbl>
1     1  21       6     2
2     2  21       6     2
3     3  22.8     4     2
4     4  21.4     6     2
5     5  18.7     8     2
6     1  21       6     2
7     2  21       6     2

Or using add_row

library(tibble)
df %>% 
    add_row(!!! {.} %>% 
         slice(seq_len(first(n))))

The unique on n is applied outside the tidyverse context. So, it should be .$n

df %>% 
    bind_rows(df[1:unique(.$n),])
  • Related