Logical Test Indexing

I need a variable containing all the dataframe rows df, where xmore than y. But for some reason, I keep getting this strange error.

> x <- c(5,6,7,8,9,10)
> y <- c(1,7,8,29,0,1)
> 
> df <- data.frame(x, y)
> 
> x.is.more <- df[,"x" > "y"]; x.is.more
data frame with 0 columns and 6 rows

The code above should have the same results as x.is.more <- df[c(1,6),], but for some reason, it doesn't work.

+4
source share
4 answers

subsetis probably the easiest way to do this:

subset(df, x>y)
   x y
1  5 1
5  9 0
6 10 1
+3
source

You can use transformif you want to add a new variable to an existing data frame

> transform(df, x.is.more= x>y)
   x  y x.is.more
1  5  1      TRUE
2  6  7     FALSE
3  7  8     FALSE
4  8 29     FALSE
5  9  0      TRUE
6 10  1      TRUE

Use withif you need a new variable

> x.is.more <- with(df, x>y)
> x.is.more
[1]  TRUE FALSE FALSE FALSE  TRUE  TRUE

If you want a subset, try

> df[ with(df, x>y), ]  # equivalent to df[ x.is.more, ]
   x y
1  5 1
5  9 0
6 10 1

subset, @James

+2

:

#dummy dataframe
df <- data.frame(x=c(5,6,7,8,9,10),
                 y=c(1,7,8,29,0,1))

#find x>y
x.is.more <- df[df$x > df$y, ]

#output
x.is.more
#   x y
#1  5 1
#5  9 0
#6 10 1
+1

! .

<

x.is.more <- df[,"x" > "y"]

,

x.is.more <- df[x > y,]
0
source

All Articles