简体   繁体   中英

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")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM