I have been searching for this a long time and never found suitable answer here. I have a variable "extern" which is a vector containing names of my data frames:
extern <- list.files(pattern = "*.csv")
extern <– c("altitude.csv", "area.csv", "farmland.csv", "GDPpercapita.csv", "population.csv")
I can load them into R like this and the characters are converted to variables. It works for me assuming my wd is the folder same as data.
for (i in 1:length(extern)) assign(extern[i], fread(extern[i], sep = ","))
But this is only case that works for me. Now I want to iterate through loaded datasets and replace all commas nad % signs by nothing "". If I put a single dataset (instead of extern[i]) there, the code works but when put to for cycle it throws an error.
for (i in 1:length(extern)) {
mutate_all(extern[i], function(x) {
str_replace_all(string = x, pattern = ",", replacement = "")
str_replace_all(x, pattern = "%", replacement = "")})
}
Error in UseMethod("tbl_vars") : no applicable method for 'tbl_vars' applied to an object of class "character"
So I tried similar think with assign() as before without any success, than somebody used eval(parse()) combo and many different thinks.
for (i in 1:length(extern)) {
assign(extern[i], mutate_all(extern[i], function(x) {
str_replace_all(string = x, pattern = ",", replacement = "")
str_replace_all(x, pattern = "%", replacement = "")}))
This is quite general problem, I encountered it many times and nothing worked so every time I had to go around. But now I have so many files that it is not possible to do it manually. Same problem is for example in data.table - I have stored column names in a vector and I wanted to do whatever. If you write there the name of the vector the data.table takes it as a name of single column and do not evaluate it. Also it is usually needed to cbind() or rbind() these files like this:
data <- rbindlist(l = list("altitude.csv", "area.csv", "farmland.csv", "GDPpercapita.csv", "population.csv"), idcol = "id")
and id like to have it easier way something like below - extern is a vector full of names (character strings)
rbindlist(l = extern, idcol = "id")
in this case it is possible to store names in the list because function itself accepts list of names, but majority of other functions including mutate_all() I used as an example, accepts variable not a character string as a name.
I hope somebody has same issue or some other way how to do it, because I really don't know and I spend searching like half year.