【问题标题】:Extract values from list of named lists in R从R中的命名列表列表中提取值
【发布时间】:2021-02-21 11:01:29
【问题描述】:

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

示例数据

set.seed(123)

data <- list('4' = list(x = rnorm(5), y = rnorm(5), z = rnorm(5)),
             '5' = list(x = rnorm(5), y = rnorm(5), z = rnorm(5)),
             '6' = list(x = rnorm(5), y = rnorm(5), z = rnorm(5)),
             '7' = list(x = rnorm(5), y = rnorm(5), z = rnorm(5)),
             '8' = list(x = rnorm(5), y = 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)): no non-missing arguments to min; 返回 Inf list()

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

【问题讨论】:

  • 使用data[['i']],您正在寻找一个名为i 的列表条目。
  • 好的,但是后来我不明白为什么调用:data[['8']],但是重写函数后不起作用?那里具体出了什么问题?
  • data[['8']] 选择名为 8 的条目。 i &lt;- '8'; data[[i]] 还会选择名为 8 的条目。但这里是i
  • 感谢您的快速回复!所以,本质上两者都应该是相同的,但是为什么一个最终成为错误,而另一个却没有呢?更具体地说,我确实了解第一部分(直到示例函数)。但是后来我重写了函数(将i更改为'i')并且函数中断了......
  • 使用:data[[as.character(i)]]

标签: r list subset sampling


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多