Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscript out of bounds when using [[]]

Tags:

r

I'm attempting to simulate a hash map with the following code and get an index out of bounds in the if statement?

I'm not sure what is causing this since printing the initial null values from a loop works fine.

strings <- c("string1","string2","string3")

test <- NULL

for (i in 1:length(strings)) {
  print(is.null(test[[strings[i]]]))
  }

for (i in 1:length(strings)) {
  if (is.null(test[[strings[i]]])) {
    test[[strings[i]]] <- 1
    }
  }
like image 849
Jared Avatar asked May 26 '26 09:05

Jared


1 Answers

Instead of test <- NULL you can initialize test as a list:

test <- list()

This should remove the error message and give the desired result:

> test
#$string1
#[1] 1
#
#$string2
#[1] 1
#
#$string3
#[1] 1
like image 184
RHertel Avatar answered Jun 01 '26 01:06

RHertel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!