How can I turn a String into a variable name in R

r, string, variables

Solution

You were looking for `get`. Your code would look like this:

file_names  <- list.files()
short_names <- substr(file_names, 1, 6)

for (i in seq_along(file_names)) {
    assign(short_names[i], read.csv(file_names[i], header = FALSE))
    colnames(get(short_names[i])) <- c('Date', 'Time', 'Open', 'Close', 'Volume')
}

but it seems easier to use the `col.names` option from the `read.*` functions, try:

assign(short_names[i], read.csv(file_names[i], header = FALSE,
                                col.names = c('Date', 'Time', 'Open',
                                              'Close', 'Volume'))

and if you are not familiar with the *apply family of functions, your whole loop can be replaced with:

mapply(assign, short_names, lapply(file_names, read.csv, header = FALSE,
                                   col.names = c('Date', 'Time', 'Open',
                                                 'Close', 'Volume'))

Problem

I am working with a bunch of currency data .csv files. These .csv come without a header, which I am trying add, using the colnames function. ``` colnames(variable_name) <- c('Date', 'Time', 'Open', 'Close', 'Volume') ``` The data import and the assignment of the column headers is supposed to be done automatically using a for loop. The name of the data frame is part of the file name. ``` file_names <- list.files() for (i in 1:length(file_names)){ assign(substr(file_names,1,6)[i], read.csv(file_names[i], header=F)) colnames(variable_name) <- c('Date', 'Time', 'Open', 'Close', 'Volume') } ``` How can I manage to input the variable_name into the colnames function. I tried using: ``` colnames(substr(file_names,1,6)[i]) ``` But that would give me the input "AUDUSD", and I need to input AUDUSD without the quotation marks. So how can I manage to convert the String into a variable name I can use here? Or maybe my approach is completly wrong here? Thanks alot! Chris

Original source

Related problems