I want to plot a graph using a for loop in R. I have tried using matlab and it works without problem.

I have tried following code in matlab:

#matlab code
d=0:400;
for h=1:10:50
w=1./(1+(d.^2/h^2));
plot(d,w);
hold on
end
xlabel('Distance(km)')
ylabel('Weight')

I tried the following code in R, however it does not seem to work

#R code
h <- c(1,20,50,100,200,400)
d <- seq(40, 420, by=20)
for (i in 1:d) {
  w <- 1/(1+(i^2/h^2))
  lines(d,w)
    }

How can I reproduce the above matlab code in R using for loop?

1 Answers

0
cardinal40 On

Here's one possibility using the Tidyverse packages:

library(tidyverse)

df <- 
  tibble(
    d = rep(0:400, 5),
    h = rep(c(1, 11, 21, 31, 41), each = 401)
  ) %>% 
  mutate(w = 1 / (1 + (d ^ 2 / h ^ 2)))

df %>% 
  mutate(h = factor(h)) %>% 
  ggplot(aes(x = d, y = w, color = h)) +
  geom_line() + 
  labs(
    x = "Distance (km)",
    y = "Weight"
  ) +
  theme(legend.position = "bottom")

enter image description here