Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - brevity when subsetting?

Tags:

r

I'm still new to R and do all of my subsetting via the pattern:
data[ command that produces logical with same length as data ]
or
subset( data , command that produces logical with same length as data )

for example:

test = c("A", "B","C")
ignore = c("B")
result = test[ !( test %in% ignore ) ]
result = subset( test , !( test %in% ignore ) )

But I vaguely remember from my readings that there's a shorter/(more readable?) way to do this? Perhaps using the "with" function?

Can someone list alternative to the example above to help me understand the options in subsetting?

like image 470
SFun28 Avatar asked Dec 16 '22 12:12

SFun28


1 Answers

I don't know of a more succinct way of subsetting for your specific example, using only vectors. What you may be thinking of, regarding with, is subsetting data frames based on conditions using columns from that data frame. For example:

dat <- data.frame(variable1 = runif(10), variable2 = letters[1:10])

If we want grab a subset of dat based on a condition using variable1 we could do this:

dat[dat$variable1 < 0,]

or we can save ourselves having to write dat$* each time by using with:

with(dat,dat[variable1 < 0,])

Now, you'll notice that I really didn't save any keystrokes by doing that in this case. But if you have a data frame with a long name, and a complicated condition it can save you a bit. See also the related ?within command if you're altering the data frame in question.

Alternatively, you can use subset which can do essentially the same thing:

subset(dat, variable1 < 0)

subset can also handle conditions on the columns via the select argument.

like image 54
joran Avatar answered Dec 21 '22 22:12

joran