Question

Small example

 A <- c("kl", "ck", "nK", "jk")
    B <- data.frame( CK = 1:10, JK = c ("kl", "cdf", "ck", "snp", "je1","cki", 
"nK", "cd12", "jk", "lm"), np = 31:40)
B
   CK   JK np
1   1   kl 31
2   2  cdf 32
3   3   ck 33
4   4  snp 34
5   5  je1 35
6   6   cki 36
7   7   nK 37
8   8 cd12 38
9   9   jk 39
10 10   lm 4

I want to select rows where B$Jk has values equal to A, preserving the order. Thus output will have whole row with value ("kl", "ck", "nK", "jk")

   CK   JK np
1   1   kl 31
2   3   ck 33
3   7   nK 37
4  9   jk 39

My trial:

B[B$JK %in% A] 
Error in `[.data.frame`(B, B$JK %in% A) : undefined columns selected

I know this is too basic question to ask, however I did not know.

Was it helpful?

Solution

You're just missing a comma:

B[B$JK %in% A,]

 CK JK np
1  1 kl 31
3  3 ck 33
7  7 nK 37
9  9 jk 39

The comma indicates that you are subsetting by rows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top