Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R functions to trim data frame

below is a sample data frame and I would like to trim and data frame by extracting different columns:

> c1<-c(1:10)
> c2<-c(1,2,3,4,5,4,3,2,1,9)
> c3<-c(11:20)
> df<-data.frame(c1,c2,c3)
> df
   c1 c2 c3
1   1  1 11
2   2  2 12
3   3  3 13
4   4  4 14
5   5  5 15
6   6  4 16
7   7  3 17
8   8  2 18
9   9  1 19
10 10  9 20

Say if I wanna skip the entire top and bottom row, which shall be like:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a function where I can extract the data frame or to eliminate certain rows? Thanks so much.

>Solution :

The dplyr package has multiple functions to assist with this

slice keeps the rows or requested (or removes those with a "-" in front of them)

df |>
  slice(-c(1, n()))

or equivalently,

slice(df, -c(1, n()))

filter let’s you keep the rows with specified conents

df |>
  filter(c1 > 1)

Commas act like "and" (so both requirements must be true)

df |>
  filter(
    c1 > 1,
    c3 < 20
  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading