Is there better way to:
- Get rid of for loops
- Remove legend and mark the line colors on the line itself elegantly ?
Please find the reprex below along with my attempt to make secondary axis.
library(tidyverse)
l = data.frame(L = integer())
l_aggr <- function(mydata){
for (j in 1:3){
for(i in 1:10){
l[i,j] = sum(i*j,j*i+1)
}
l = as.data.frame(l)
}
return(l)
}
l_aggr(1) %>%
gather(ax, va) %>%
mutate(year = rep(2000:2009,3)) %>%
ggplot(aes(x= year,y= va, col = ax)) +
geom_line() +
scale_y_continuous(sec.axis = ~.*2, "relative L")
Attempt for creating another axis
l_aggr(1) %>%
mutate(year = 2000:2009) %>%
ggplot(aes(x= year)) +
geom_line(aes(y=L, col = "L")) +
geom_line(aes(y=V2, col = "V2")) +
geom_line(aes(y=V3*.5, col = V3)) +
scale_y_discrete(sec.axis = ~.*2, "relative V3")
I can only answer the 1st part now. If you're OK with base R functions (you were not in some earlier threads), you can use outer
:
l = data.frame(L = integer())
l_aggr <- function(mydata){
for (j in 1:3)
{
for(i in 1:10)
{
l[i,j] <- sum((i * j), ((j * i) + 1))
}
l <- as.data.frame(l)
}
return(l)
}
l_aggr(mydata = 1)
#> L V2 V3
#> 1 3 5 7
#> 2 5 9 13
#> 3 7 13 19
#> 4 9 17 25
#> 5 11 21 31
#> 6 13 25 37
#> 7 15 29 43
#> 8 17 33 49
#> 9 19 37 55
#> 10 21 41 61
data.frame(outer(X = 1:10,
Y = 1:3,
FUN = function(i, j) (2 * (i * j) + 1)))
#> X1 X2 X3
#> 1 3 5 7
#> 2 5 9 13
#> 3 7 13 19
#> 4 9 17 25
#> 5 11 21 31
#> 6 13 25 37
#> 7 15 29 43
#> 8 17 33 49
#> 9 19 37 55
#> 10 21 41 61
Created on 2019-06-07 by the reprex package (v0.3.0)
If you want, you can name the columns finally with names
as you want.
For the 2nd part, can you please provide an example of the desired result?
By the way, your code is not a reprex
, as you didn't include the package calls. I added library(tidyverse)
, and I hope you won't mind.
1 Like
system
Closed
3
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.