从R中的命名列表列表中提取值

问题描述

基于具有列表xyz值的子列表的名称,我想从子列表中提取xyz值的样本。注意:列表不是从1开始。

示例数据

set.seed(123)

data <- list('4' = list(x = rnorm(5),y = rnorm(5),z = rnorm(5)),'5' = list(x = rnorm(5),'6' = list(x = rnorm(5),'7' = list(x = rnorm(5),'8' = list(x = rnorm(5),z = rnorm(5)))

提取随机值的功能(源自here

我具有以下功能来从列表中采样随机xyz值:

get_elements <- function(data,i) {
  #select the main list
  tmp <- data[[i]]
  #Check the length of each sublist,select minimum value
  #and sample 1 number from 1 to that number
  rand_int <- sample(min(lengths(tmp)),1)
  #select that element from each sub-list
  sapply(tmp,`[[`,rand_int)
}

功能示例

# Show list number 8
data[['8']]
#> $x
#> [1]  0.3796395 -0.5023235 -0.3332074 -1.0185754 -1.0717912
#> $y
#> [1] 0.30352864 0.44820978 0.05300423 0.92226747 2.05008469
#> $z
#> [1] -0.4910312 -2.3091689  1.0057385 -0.7092008 -0.6880086

# Extract random combination from list 8
get_elements(data,'8')
#>           x           y           z 
#> -0.33320738  0.05300423  1.00573852

重写功能

使用与上述相同的功能,我将i替换为'i'

get_elements <- function(data,i) {
  tmp <- data[['i']]                       # <-- changed i to 'i'
  rand_int <- sample(min(lengths(tmp)),1)
  sapply(tmp,rand_int)
}

错误和问题

get_elements(data,8)

以min(lengths(tmp))为单位的警告:min没有非缺失的参数; 返回Inf list()

功能突然中断,我不明白为什么?此错误的原因是什么?

解决方法

尝试一下:

get_elements <- function(data,i) 
{
  tmp <- data[[paste(i)]]
  rand_int <- sample(min(lengths(tmp)),1)
  sapply(tmp,`[[`,rand_int)
}

您的初始代码失败的原因是因为“ i”被理解为“字符i”,而不是“将变量i转换为字符”。参见:

i = 1
print("i") # i
print(i) # 1