【问题标题】:How can I remove an element from a list by index, when the index matches a value from another list?当索引与另一个列表中的值匹配时,如何按索引从列表中删除元素?
【发布时间】:2023-02-16 03:59:23
【问题描述】:

我有一个包含值的列表 (list_a),我想从该列表中删除具有特定索引的所有值。为此,我已经有了一个单独的列表 (list_b),其中包含我要删除的所有索引作为其值。现在我想从 list_a 中删除所有索引与 list_b 中的值相匹配的值。

为了便于理解这里举个例子:

list_a <- list("One", "Two", "Three", "Four", "Five") # original list

list_b <- list(2, 4) # indexes that I want to remove from list_a

# Desired Output:
# [1] "One" "Three" "Five" 

我尝试执行以下操作:

list_c <- list_a[-c(list_b)]
# But got the following error:
# Error : invalid argument to unary operator

因为我知道我可以通过以下方式删除索引:

list_c <- list_a[-c(2,4)]

但是我不想事先知道我想删除的值,我不能使用一个列表作为参数来删除另一个列表的索引吗?

【问题讨论】:

  • 索引值必须是一个向量,而不是一个列表,所以 unlist(list_a[-unlist(list_b)]) 会得到你想要的。

标签: r list indexing


【解决方案1】:

您不能使用列表进行索引;你需要使用atomic vector。您可以通过以下方式解决问题

  1. 创建 list_b 作为数字向量开始:
    list_b <- c(2, 4)
    list_a[list_b]
    
    1. 或使用as.numeric()unlist()转换为原子向量。
    # either
    list_a[as.numeric(list_b)]
    # or
    list_a[unlist(list_b)]
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 2017-12-16
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多