Home > front end >  R: obtaining the values of a dataframe based on an ordered vector
R: obtaining the values of a dataframe based on an ordered vector

Time:10-23

I would like to obtain the specific values of a dataset. For example:

df <-read.table(header=TRUE, text="id 
                A187 
                A180 
                C168 
                H897 
                D987 
                C098 
                Q897 
                P987 
                L876")

Lets say I have a vector V = 1 4 5. I basically want to select th first, and fourth elements of the id such as:

df_new <-read.table(header=TRUE, text="id 
                A187 
                H897 
                D987")

CodePudding user response:

Use the V as row index and specify the drop = FALSE as there is a single column and it is a data.frame (to avoid dropping the dimensions as drop = TRUE by default)

 df[V, , drop = FALSE]

-output

   id
1 A187
4 H897
5 D987

data

V <- c(1, 4, 5)
  • Related