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
The last n rows of the data frame can be accessed by using the in-built tail() method in R.
You can reference a column of an R data frame via the column name. If the data was loaded from a CSV file, the column name is the name given to that column in the first line (the header line) of the CSV file.
To select a column in R you can use brackets e.g., YourDataFrame['Column'] will take the column named “Column”. Furthermore, we can also use dplyr and the select() function to get columns by name or index. For instance, select(YourDataFrame, c('A', 'B') will take the columns named “A” and “B” from the dataframe.
ncol() function in R Language is used to return the number of columns of the specified matrix. Syntax: ncol(x)
just use ncol()
to get the index of the last col
data[,ncol(data)]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With