R语言中命名列表子列表值提取函数报错原因排查
Hey there! Let's break down exactly what's happening here:
The Core Issue: Literal vs. Variable Indexing
When you changed tmp <- data[[i]] to tmp <- data[['i']], you made a critical shift in how R interprets the index:
data[[i]]uses the value of the variablei(in your case, 8) to look up the element in the list. Depending on whetheriis a number or string, this will either index by position or by the list's names.data[['i']]looks for an element with the literal string name "i" in your list. Yourdataobject only has sublists named "4", "5", "6", "7", "8" — there's no sublist called "i"! Sotmpends up beingNULL.
Why the Warning Happens
When tmp is NULL, any operation that tries to access its elements (like lengths(tmp)) returns an empty vector. The min() function can't compute a minimum from an empty set of values, so it throws that warning: "min(lengths(tmp)): no non-missing arguments to min; returning Inf" and returns Inf. Since there's no valid data in tmp to sample from, your function ends up returning an empty list.
How to Fix It
If you want to target the sublist corresponding to the value of i (e.g., 8 → the sublist named "8"), stick with the original syntax, or explicitly convert i to a character if you're passing a number:
# Option 1: Use the variable directly (works if i is a string, or if R can coerce it to match a name) tmp <- data[[i]] # Option 2: Explicitly convert numeric i to a character to match list names tmp <- data[[as.character(i)]]
This will correctly grab the sublist you intended (the one named "8" when you call get_elements(data, 8)), and your sampling logic will work as expected.
内容的提问来源于stack exchange,提问作者user213544

