0

I have loop values storing into a list when I run the code below, but when I call the list again, 19 null values display. Any help is greatly appreciated.

my_list <- list()
my_list

nums <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) #create number list
print(nums)

for(i in nums){
  output <-cat(paste(i^2,""))
  my_list[i] <- output
}

my_list

Values appear as follows after running the last two lines: 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400

When I run my_list again, I get the following but want the values that were shown to appear.

[[1]] 
Null

[[2]]
Null
.
.
.
[[19]]
Null
wibeasley
  • 5,000
  • 3
  • 34
  • 62

1 Answers1

0

Two things:

  1. Don't use cat(); paste() is sufficient for your goal.
  2. Refer to list elements with double brackets (ie, my_list[[i]] instead of my_list[i]).
my_list <- list()

nums <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) #create number list

for(i in nums){
  output       <- paste(i^2,"")
  my_list[[i]] <- output
}
my_list

Output:

[[1]]
[1] "1 "

[[2]]
[1] "4 "

...

[[20]]
[1] "400 "
wibeasley
  • 5,000
  • 3
  • 34
  • 62