I am having an issue using a user-defined function within a for
loop, as shown in the code below. It seems to be an issue with the way I'm trying to input an index into the function, as I get the below message whenever I try to run it.
Error: $ operator is invalid for atomic vectors
However, the function runs fine on its own. It returns the correct result when I use it with one of the variables outside the loop.
Essentially, what I'm trying to do is:
- run the function on all variables that store the data I've imported
- store the data generated by the function in that same variable, overwriting the original data.
It could be that my whole way of going about this is wrong. Is it even possible to call variables using a list of their names? Example input data is imported into R using read.delim
and looks like this:
There are 1,400 or so files being read in.
## Import files:
temp = list.files(pattern="*.csv") #Filenames from working directory
for (i in 1:length(temp)) {
#Clean data to include only RGB
assign(temp[i], read.delim(temp[i],sep=";", header = T, nrows = 6))
}
allvars <- ls(all.names = T) #List all variables
#Find RGB classes and name
getClasses <- function(variable) {
red <- variable$R[3:5]
green <- variable$G[3:5]
blue <- variable$B[3:5]
classes <- data.frame(red, green, blue)
print(classes)
}
#This is where the problem happens:
for (i in 1:length(allvars)) {
#Apply getClasses function to current variable and store new data
assign(allvars[i], getClasses(allvars[i]))
}
#Error: $ operator is invalid for atomic vectors