0

I have a list of colors called mergedColors. From this list of colors, I use a for() loop to go though and create a matrix corresponding to each unique color. Up until this point, everything works fine. I then want to go and continue to alter/edit the matrices in the loop after I have initially created them. In the example, I try to change the name of the third column. However, I'm not entirely sure how to go about doing that. When I try to call them through the same syntax that I used to create them,

colnames(paste("merged",each,sep="_"))[3] = "Temp"

R returns an error: "target of assignment expands to non-language object". How should I call the matrices I just created while still inside the loop?

Sample data:

mergedColors = c("red", "blue", "green", "red", "black", "blue", "blue", "green", "yellow", "red")
table(mergedColors)



for(each in unique(mergedColors)){ 

  assign(paste("merged",each,sep="_"), as.matrix(cbind(cars, c(each))))
  #colnames(paste("merged",each,sep="_"))[3] = "Temp"

} 
Hack-R
  • 22,422
  • 14
  • 75
  • 131
czhu550
  • 41
  • 4

1 Answers1

2

You just need to use get to tell R that the thing you're pasting is referring to an object.

Like this:

tmp <- get(paste("merged",each,sep="_"))
colnames(tmp)[3] = "Temp"

> head(tmp)
     speed dist  Temp    
[1,] " 4"  "  2" "yellow"
[2,] " 4"  " 10" "yellow"
[3,] " 7"  "  4" "yellow"
[4,] " 7"  " 22" "yellow"
[5,] " 8"  " 16" "yellow"
[6,] " 9"  " 10" "yellow"

Here's the full loop:

for(each in unique(mergedColors)){ 

  assign(paste("merged",each,sep="_"), as.matrix(cbind(cars, c(each))))
  #colnames(paste("merged",each,sep="_"))[3] = "Temp"
  tmp <- get(paste("merged",each,sep="_"))
  colnames(tmp)[3] = "Temp"
  assign(paste("merged",each,sep="_"), tmp)

} 
Hack-R
  • 22,422
  • 14
  • 75
  • 131
  • But with that you create a new matrix I think. It does not alter the name of the actuel matrix or am I wrong? – Alex Jul 13 '16 at 21:22
  • @Alex Right, so you just need to run the `assign` operation like you did before to overwrite it. I'll add the full loop to show you. – Hack-R Jul 13 '16 at 21:23
  • Also take a look at this: http://stackoverflow.com/questions/14464442/using-get-with-replacement-functions – Alex Jul 13 '16 at 21:27
  • @Alex Interesting. Just to be clear, does this solution work for you? It seems to produce the desired result for me; just wanted to check. – Hack-R Jul 13 '16 at 21:37
  • @ Hack-R It is not my question ;) But I guess it works although I think their might be a better solution. – Alex Jul 13 '16 at 21:39
  • @Alex This is probably the best way to go about it given that the actual data I'm working with is more complex and I need to perform several changes to each one. Having a single simple matrix I can call is very convenient. Thanks! – czhu550 Jul 13 '16 at 23:18