假设我有一个索引和值的列表。
indx_list <- list(1,2,c(3,4),5,c(6,7,8))
val_list <- list(0.1,0.6,c(0.8,0.9),0.3,c(0.4,0.8,0.5))
然后,我想通过删除索引c(4,7)
和相应的值c(0.9,0.5)
来更新这两个列表。使用lapply
和setdiff
很容易做到这一点。例如:
indx_list_new <- lapply(indx_list,function(x) setdiff(x,c(4,7)))
val_list_new <- lapply(val_list,function(x) setdiff(x,c(0.9,0.5)))
但是,我事先不知道我将删除哪些索引和相应的值。
set.seed(1234)
indx_flag <- sample(seq(8),2)
您还可以看到一些值是重复的(例如0.8),因此使用setdiff
实际上可能会删除错误位置的值。
问题
1)我仍然可以使用lapply
和setdiff
来更新indx_list
,但是如何更新val_list
中的值?
2) lapply
是这里最有效的解决方案吗?我将拥有包含数千个元素的列表,每个元素可以是数百个索引/值的向量。
编辑
列表中的每个元素(最高级别)实际上都有一个特定的含义,所以我想保留列表结构。
发布于 2019-04-08 07:01:18
相反,将你的数据排列成一个“整洁”的表示形式
df = data.frame(
indx = unlist(indx_list),
val = unlist(val_list),
grp = factor(rep(seq_along(indx_list), lengths(indx_list)))
)
操作或多或少是透明的
base::subset(df, !indx %in% c(4, 7))
indx val grp
1 1 0.1 1
2 2 0.6 2
3 3 0.8 3
5 5 0.3 4
6 6 0.4 5
8 8 0.5 5
使用subset()
与使用df[!df$indx %in% c(4, 7), , drop = FALSE]
类似。(我使用factor()
来允许空组,即没有相应值的级别)。
发布于 2019-04-08 06:58:55
这里尝试使用relist
和Map
删除相同的点:
Map(`[`, val_list, relist(!unlist(indx_list) %in% c(4,7), indx_list))
#[[1]]
#[1] 0.1
#
#[[2]]
#[1] 0.6
#
#[[3]]
#[1] 0.8
#
#[[4]]
#[1] 0.3
#
#[[5]]
#[1] 0.4 0.5
https://stackoverflow.com/questions/55564225
复制相似问题