Real Name
Real Name

Reputation: 5

r: subsetting with square brackets not working

I made data frame called x:

a  b
1  2
3  NA
3  32
21 7
12 8

When I run

y <- x["a">2,]

The object y returned is identical to x. If I run

y <- x["a" == 1,]

y is an empty frame.

I made sure that the names of the x data frame have no white spaces (I named them myself with names() ) and also that a and are numeric.

PS: If I try

 y <- x["a">2]

y is also returned as identical to x.

Upvotes: 0

Views: 3032

Answers (2)

rafa.pereira
rafa.pereira

Reputation: 13807

A simple alternative would be using data.table

library(data.table)

setDT(x)

y <- x[ a > 2, ]

y <- x[ a == 1, ]

Upvotes: 0

Val
Val

Reputation: 7023

You're making an error in referencing the column of your data.frame x.

"a">2 means character a bigger than two, not variable a of data.frame x. You need to add either x$a or x["a"] to reference your data.frame column.

try

y <- x[x$a >2 ,]

or

y <- x[x["a"] >2 ,]

or even more clear

ix <- x["a"] > 2

y <- x[ix,]

Upvotes: 5

Related Questions