Home > OS >  extract every nth element of a column in a dataset
extract every nth element of a column in a dataset

Time:05-22

Let suppose I have a dataset, named "df", with many columns, and I need to extract every fifth element of only one column, named “country”. Could anyone suggest a sample code for it?

CodePudding user response:

Just use seq to create a sequence of the numbers you want, and use [seq,] for indexing. Aditionally, to select a given oclumn, use [,"col_name"]

df <- iris
row_seq <- seq(5, nrow(df), by=5)
df[row_seq,]
#>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#> 5            5.0         3.6          1.4         0.2     setosa
#> 10           4.9         3.1          1.5         0.1     setosa
#> 15           5.8         4.0          1.2         0.2     setosa
#> 20           5.1         3.8          1.5         0.3     setosa
...

Created on 2022-05-22 by the reprex package (v2.0.1)

CodePudding user response:

Maybe something like this:

library(tidyverse)

tibble(country = LETTERS) |> 
  filter(row_number() %% 5 == 0)
#> # A tibble: 5 × 1
#>   country
#>   <chr>  
#> 1 E      
#> 2 J      
#> 3 O      
#> 4 T      
#> 5 Y

Created on 2022-05-22 by the reprex package (v2.0.1)

CodePudding user response:

A base solution is:

df[seq_len(nrow(df)) %% 5 == 0, ]

Also, you could recycle a logical vector:

df[c(rep(FALSE, 4), TRUE), ]
  •  Tags:  
  • r
  • Related