When a subset of R needs to include `which` or can I just put a logic test?

Let's say I have a data frame dfand want a subset of it based on the value of column a.

df <- data.frame(a = 1:4, b = 5:8)
df

Do I need to include a function in brackets whichor can I just include a logic test?

df[df$a == "2",]
#  a b
#2 2 6
df[which(df$a == "2"),]
#  a b
#2 2 6

Everything seems to work the same way ... I was getting some strange results in a large data frame (i.e. getting blank lines as well as correct ones), but as soon as I cleaned up the environment and restarted my script it worked fine.

+6
source share
1 answer

df$a == "2" , which(df$a=="2") . , , which .

:

x=c(1,NA,2,10)

x[x==2]
[1] NA  2
x[which(x==2)]
[1] 2
x==2
[1] FALSE    NA  TRUE FALSE
which(x==2)
[1] 3
+1

Source: https://habr.com/ru/post/1016872/


All Articles