Can't tell left() from right() in R

Viewed 155

Are R's gdata::left() and gdata::right() actually the same functions, but with different names and working exactly as they should, or am I using them incorrectly?

I have: mtcars

I want: only the last 2 columns from mtcars

(I know I could ask for this with mtcars[,(length(mtcars)-1):(length(mtcars))], but why would I if there is an easier way?)

What I want looks like this:

                    gear carb
Mazda RX4              4    4
Mazda RX4 Wag          4    4
Datsun 710             4    1
Hornet 4 Drive         3    1
Hornet Sportabout      3    2
...

It seems like right(mtcars,2) would accomplish this, but instead it gives

                     mpg cyl
Mazda RX4           21.0   6
Mazda RX4 Wag       21.0   6
Datsun 710          22.8   4
Hornet 4 Drive      21.4   6
Hornet Sportabout   18.7   8
...

Which is exactly the same as left(mtcars,2):

                     mpg cyl
Mazda RX4           21.0   6
Mazda RX4 Wag       21.0   6
Datsun 710          22.8   4
Hornet 4 Drive      21.4   6
Hornet Sportabout   18.7   8
...

My main question is, what is the simplest way to get the rightmost n columns from a dataframe? I want something, hopefully base R, that doesn't require knowing the number of total number of columns of mtcars.

2 Answers

There appears to be a weird/silly bug in gdata. If you look at the source for left/right you will see that both functions get a UseMethod("left"). As far as I understand, that means that calls for either with a data.frame, will result in a call to left.data.frame. Indeed, if I type in

right <- function(x, n=6L) UseMethod("right")

then right(mtcars,2) works as expected.

We can use tail on the column names from base R to get the last n columns

mtcars[tail(names(mtcars), 2)]

Or head to get the first n columns

mtcars(head(names(mtcars), 2)]
Related