简体   繁体   中英

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.

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,]

A simple alternative would be using data.table

library(data.table)

setDT(x)

y <- x[ a > 2, ]

y <- x[ a == 1, ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM