[英]Extract values from list of named lists in 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), 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)))
提取隨機值的函數(派生自此處)
我有以下函數來從列表中隨機抽樣 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 列表()
突然功能中斷,我不明白為什么? 這個錯誤的原因是什么?
嘗試這個:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.