0

I have a data frame(s) df1,df2,... that I am accessing through a for loop (R for loop I know...) I need to assign the last column (y variable) to be a factor. I am attempting to do it like this:

get(paste0('df',x))[,ncol(get(paste0('df',x)))] <- as.factor(get(paste0('df',x))[,ncol(get(paste0('df',x)))])

however I am getting the 'target of assignment expands to non-language object' error when I try to do this.

Why is this not behaving the same way as this?

df1[,19] <- as.factor(df1[,19])

and is there a way to assign my columns as factors given that it must be done through a process similar to this?

alants
  • 3
  • 1
  • 3
    You cannot assign via `get()`. Code generally avoid `get()` and `set()` which don't work with data.frame extraction. When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. There is probably a more R-like way to do what you are trying to do that doesn't involved `get()`. – MrFlick Apr 02 '18 at 20:41
  • 5
    I'm 99% sure that if you show us more about your case we can end up with something much more elegant – moodymudskipper Apr 02 '18 at 20:56
  • 1
    @MrFlick, do you mean `assign()`? (I agree, both functions should generally be avoided and will not work well here.) – r2evans Apr 02 '18 at 21:58
  • @r2evans Yep. I meant assign(). My bad. – MrFlick Apr 02 '18 at 22:09
  • 1
    Seeing unnecessary use of `get()` in R is remniscent of excel's `INDIRECT` function, and should be avoided about as urgently. – r2evans Apr 02 '18 at 22:20

0 Answers0