1

I have a dataframe (locs.new) of daily distances traveled by radiotagged birds. I'm trying to create a function that calls a for loop that creates a subset for the ith sparrow (identified by a character variable "anillo") and then ggplot a bar graph with the xAxis=Number of the Location (NoFrec) and yAxisDistance traveled (Distance). This is what I have tried:

   plotDist <- function (x) {
     v<-levels(locs.new$anillo)
     as.vector(v)

     for (i in v) {

       print(i)
       da<-subset(locs.new,anillo==i)
       dat<-subset(da, select = c(NoFrec, Distance))
       plot(dat$NoFrec~ dat$Distance)
       print(ggplot(dat, aes(x=NoFrec, y= Distance))) +geom_col() +    ggtitle(as.character(i))

     }
   }
   plotDist(locs.new)

If I isolate the code from the for loop and individually create each dataset it works perfectly fine:

i<-"XEN010"
da<-subset(locs.new,anillo==i)
dat<-subset(da, select = c(NoFrec, Distance))
plot(dat$NoFrec~ dat$Distance)
print(ggplot(dat, aes(x=NoFrec, y= Distance))) +geom_col() + ggtitle(as.character(i))

resulting in: enter image description here but the problem arises when I insert this code in the for loop. It plots the graphs...but empty of bars and without the Title. Thanks in advance for any suggestions!

  • It's easier to help you if you 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. – MrFlick Oct 30 '18 at 20:16
  • Yes! Next time I'll do, I'm new to stack Overflow. Thank you – Annamaria Oct 30 '18 at 22:34

1 Answers1

1

Because of the location of your closing bracket ), your print statement only outputs the ggplot() object, i.e. excluding the geom_col and the ggtitle results. These latter two statements produce your bars and your title. Outside of the function, this does not matter. Inside of the function, it does.

Replace

print(ggplot(dat, aes(x=NoFrec, y=Distance))) + geom_col() + ggtitle(as.character(i))

by

print(ggplot(dat, aes(x=NoFrec, y=Distance)) + geom_col() + ggtitle(as.character(i)))

and try again?

NB It would have been helpful if the question would have included some sample data.

RUL
  • 268
  • 2
  • 12
janverkade
  • 124
  • 1
  • 8