我正在尝试使用以下代码模拟哈希映射并在if语句中获取超出范围的索引?
我不确定是什么导致这个,因为从循环打印初始空值工作正常.
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
}
}
Run Code Online (Sandbox Code Playgroud)
而不是test <- NULL你可以初始化test为列表:
test <- list()
Run Code Online (Sandbox Code Playgroud)
这应该删除错误消息并提供所需的结果:
> test
#$string1
#[1] 1
#
#$string2
#[1] 1
#
#$string3
#[1] 1
Run Code Online (Sandbox Code Playgroud)