-1

I have a data frame df, which is as follows. The left-hand side is the row names and the first column is the corresponding values.

              v1   
 a177:a1297  0.1
 a177:a842   0.2
 a177:a796   0.4
 a24:a1437   0.3
 a24:a1256   0.6
 a24:a762    0.7

I have a vector of characters which are the row names of df. The vector is dfnames

  str(dfnames)
  chr [1:5] "a177:a1297" "a177:a842" "a177:a796" "a24:a1437" "a24:a1256" "a24:a762"

If I extract one value based on a specific row name, it would be:

    df["a177:a1297",]
   [1]  0.1 

Now I want to extract all the values of df based on dfnames

  df[dfnames,]
  [1] NA NA NA NA NA NA

Could anyone tell me how to extract the values of df based on a vector that contains the row names of df?

4
  • 1
    That's weird, it works for me. I get > df[dfnames, ] \n [1] 0.1 0.2 0.4 0.3 0.6 0.7 Commented Jun 8, 2017 at 20:53
  • 1
    Passing a string should work, please make your problem reproducible. Try this example: df1 <- mtcars[1:10, 1:3]; myRows <- c("Valiant", "Duster 360"); df1[myRows, ] Commented Jun 8, 2017 at 20:57
  • 1
    Possible duplicate: stackoverflow.com/questions/23652566/… Commented Jun 8, 2017 at 21:02
  • That is what I want. Thank you very much. Commented Jun 8, 2017 at 21:12

1 Answer 1

3

You can do:

df[which(row.names(df) %in% dfnames),]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.