1

If I create a simple data frame using:

x <- 1:100
y <- x*2
df <- data.frame(x,y)

and then I try sub selecting where x>30 and x<40 by doing the following

df[df$x>30 && df$x<40]

I get:

data frame with 0 columns and 100 rows

I'd like the understand why I get that and how to fix it.

Frank
  • 66,179
  • 8
  • 96
  • 180
user975917
  • 305
  • 3
  • 13
  • 2
    Just for future searches: I think that the proper term for what you are doing is "subsetting". Using the right term will allow you to find better solution to your problems (in any case). – SabDeM Jul 18 '15 at 19:08

2 Answers2

4

You seem to have two errors, try this instead:

 df[df$x>30 & df$x<40,]
#     x  y
# 31 31 62
# 32 32 64
# 33 33 66
# 34 34 68
# 35 35 70
# 36 36 72
# 37 37 74
# 38 38 76
# 39 39 78

Explanation:

The first error is that you are using && instead of &. You want the first form if you are sure there is a comparison of vectors of length one. See this question for details.

The second one, is that you are missing a comma (","). Writing the condition for subsetting first, then a comma, then nothing, will select the rows that satisfy this condition.

You can check the differences on subsets with that same df when you try df[], df[1,] and df[,1].

Community
  • 1
  • 1
erasmortg
  • 3,246
  • 1
  • 17
  • 34
1

just to add some variety of solutions, there other ways to do so. Another way is with the subset function and/or with %in% (note the different behaviour):

subset(df, x > 30 & x < 40)
subset(df, x %in% c(31:39))
df[df$x %in% c(31:39), ]

or with dplyr:

library(dplyr)
# Standart dplyr notation
df %>% filter(x > 30, x < 40)
# Non-Standart dplyr notation
df %>% filter(x > 30 & x < 40)

all have the same result:

    x  y
31 31 62
32 32 64
33 33 66
34 34 68
35 35 70
36 36 72
37 37 74
38 38 76
39 39 78
SabDeM
  • 7,050
  • 2
  • 25
  • 38
  • 1
    with dplyr you can pass the filter conditions as multiple arguments, avoiding the `&` operator that was tripping up the OP: `df %>% filter(x > 30, x < 40)` – Sam Firke Jul 18 '15 at 19:29
  • @SamFirke yes I forget that!, thank you for the feedback, I update my post. – SabDeM Jul 18 '15 at 19:31