user1535147
user1535147

Reputation: 1475

In R, How to select a column in a dataframe by using a variable?

I am trying to get the column of a dataframe using a variable. However, there does not seems to be anyway in R to do so. How to get column of a dataframe by using a variable in R?

An idea of what I am trying to do:

getcolumn <- function(file_link, column)
{
    #get column
    employee_df=read.csv(file_link, header=TRUE)
    column_data=data.frame(employee_df[,column]) #How to get column name based on the value in the variable?
    
    print(column_data)
}

getcolumn("/home/Documents/Employee.xsl","Name")

Upvotes: 0

Views: 57

Answers (1)

LMc
LMc

Reputation: 18642

Try using drop = F:

getcolumn <- function(file_link, column)
{
    #get column
    employee_df=read.csv(file_link, header=TRUE)
    column_data=employee_df[,column , drop = F] #How to get column name based on the value in the variable?
    
    print(column_data)
}

getcolumn("/home/Documents/Employee.xsl","Name")

This should work as long as Name is a column in your csv file.

Upvotes: 1

Related Questions