Unusual behavior when using assign() in ggplot

  Kiến thức lập trình

I have isolated the problem of a more complex function with similar issues.

I have function f()

f has a for loop with a counter. Each iteration adds a new row of data to data.frame new. I printed new inside the for loop to prove that it works.

f <- function(){
  counter=0

  
  for ( i in c(2,3,4)){
  counter = counter + 1
  new <- data.frame(x=1:(5+counter),y=4:(8+counter))
  print(new)
  p <- ggplot(data=new) +
    geom_line(aes(x=x,y=y)) +
    geom_segment(x=1, xend=i, y=6, yend=6)
  
  
  assign(paste0('p', counter ), p)
}
  print(p1)
  print(p2)
  print(p3)
}
f()

output: this shows that new is properly updated each time.

> f()
  x y
1 1 4
2 2 5
3 3 6
4 4 7
5 5 8
6 6 9
  x  y
1 1  4
2 2  5
3 3  6
4 4  7
5 5  8
6 6  9
7 7 10
  x  y
1 1  4
2 2  5
3 3  6
4 4  7
5 5  8
6 6  9
7 7 10
8 8 11

Each iteration should use the ‘updated’ data.frame, new. The ggplot has a geom_line and a geom_segment layer. The plot is initially assigned to p and then assigned to assign(paste0('p', counter ), p). At the end, I should have 3 plots. p1, p2, and p3. Each one should have an updated geom_line and an updated geom_segment. But shown here, only the geom_segment gets updated, and not the geom_line layer.

When I instead use print(p) inside the for loop, it prints as expected. This makes me think the problem is with the assign function. Any suggestions?
enter image description here
enter image description here
enter image description here

LEAVE A COMMENT