'Refer to the last column in R
I am trying to do some manipulation on the last column in a generic way.
I found here on the forums this nice piece of code that returns the name of the last columns:
tail(names(train),1) #returns [1] "last"
I still can't figure out how to reference directly to my dataset's last columns as:
data$last
Solution 1:[1]
just use ncol()
to get the index of the last col
data[,ncol(data)]
Solution 2:[2]
Take the first element of the rev
ersed vector of column names:
rev(names(mtcars))[1]
[1] "carb"
Similarly, to get the last column, you can use
rev(mtcars)[1]
Solution 3:[3]
To refer to last column:
colnames(data)[ncol(data)]
Solution 4:[4]
I prefer @Troy's solution, here is another way:
train[, tail(colnames(train), 1)]
Solution 5:[5]
Troy's answer is simpler, and can be adapted to refer to "n" elements before the last column, using the ":" operator.
If you want to refer to the last threee columns, you could write:
data[,ncol(data)] # refers to the last column
data[,(ncol(data)-2):ncol(data)] # refers to the three last columns
Solution 6:[6]
Function last_col()
from tidyselect
package may help. See also answer here
Solution 7:[7]
You can use tail
, but you have to coerce to list:
tail(as.list(mtcars), 1)
This will return a vector with the contents of the column. If you want to preserve the structure, you can use:
utils:::tail.default(mtcars, 1)
so that tail
treats the input like a list. The only reason really to use this approach over Troy's are if you want more than just the last column (i.e. last N), where it becomes a lot easier to do it this way.
Solution 8:[8]
Here's an example of indexing just the last column name. Reference the
names(df1[,ncol(df1)])
:
df1 <- df1 %>%
add_column(new1 = NA, new2 = NA, new3 = NA, .after = names(df1[,ncol(df1)]))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Troy |
Solution 2 | James |
Solution 3 | cianius |
Solution 4 | |
Solution 5 | MS Berends |
Solution 6 | tlask |
Solution 7 | BrodieG |
Solution 8 | Martin Gal |