append values to list

Hello R Community.
I recently started to learn R, this is my first post.

I'm trying to add values to a list, and eventually plot the list. I tried using the c() function, but this doesn't seem to be working. How can values be appended to a list?

Keep in mind I'm very new to R, comments in the code and extra resources would be very helpful.
Thank you.

my_data <- 5
counter_var <- 0

repeat {
  counter_var <- counter_var + 1 # counts each loop
  
  my_data <- my_data * 2
  list_var <- c(counter_var, my_data)
  
  if (counter_var == 7) { # break on the 7th loop
    break
  }
}
print(list_var) # Trying to get this as a list: 1,10 2,20 3,30 4,40 5,50 6,60 7,70

The problem is that you are resetting list_var rather than adding to it. somewhere up top add

list_var <- NULL

then change the line doing the accumulation to

  list_var <- c(list_var, counter_var, my_data)

Thank you startz, That's perfect! :+1:

I think this might be what you're looking for. It won't print exactly like you said but I think it's what you're going for:

my_data <- 5
counter_var <- 0
list_var <- vector(mode="list")
repeat {
   counter_var <- counter_var + 1 # counts each loop
   
   my_data <- my_data * 2
   list_var[[counter_var]] <-c(counter_var, my_data)
   
   if (counter_var == 7) { # break on the 7th loop
      break
   }
}
print(list_var)
#> [[1]]
#> [1]  1 10
#> 
#> [[2]]
#> [1]  2 20
#> 
#> [[3]]
#> [1]  3 40
#> 
#> [[4]]
#> [1]  4 80
#> 
#> [[5]]
#> [1]   5 160
#> 
#> [[6]]
#> [1]   6 320
#> 
#> [[7]]
#> [1]   7 640

Created on 2021-11-09 by the reprex package (v2.0.1)

Thanks for taking your time to reply to my question. I've never heard of "vector(mode="list")" I'll look into this function to learn more about it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.