Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to the last column in R

Tags:

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

like image 868
thecheech Avatar asked Feb 14 '14 14:02

thecheech


People also ask

How do I get the last row of a column in R?

The last n rows of the data frame can be accessed by using the in-built tail() method in R.

How do you reference a column in R studio?

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.

How do I select the third column in R?

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.

What does NCOL mean in R?

ncol() function in R Language is used to return the number of columns of the specified matrix. Syntax: ncol(x)


Video Answer


2 Answers

just use ncol() to get the index of the last col

data[,ncol(data)] 
like image 56
Troy Avatar answered Sep 23 '22 12:09

Troy


Take the first element of the reversed vector of column names:

rev(names(mtcars))[1] [1] "carb" 

Similarly, to get the last column, you can use

rev(mtcars)[1] 
like image 22
James Avatar answered Sep 22 '22 12:09

James