【问题标题】:R - Replacing element in list of vectorsR - 替换向量列表中的元素
【发布时间】:2014-01-20 10:14:07
【问题描述】:

我有向量列表,并希望将向量分配给它的一个位置(覆盖)。这是示例代码:

for (nodeId in names(chains)) {
    chains[nodeId] <- unlist(chains[nodeId])[-1]
}

分配后,我收到许多警告,告诉我列表的长度不相等。我知道已经完成的任务不是我想要的。

有什么方法可以将chains[nodeId] 中的元素替换为对象unlist(chains[nodeId])[-1]

当我执行str(chains)str(chains[nodeId])str(unlist(chains[nodeId])[-1]) 时,我得到以下输出:

$str(chains)
List of 15
 $ 4  : chr [1:3] "root" "alcohol< 9.85" "totalSulfurDioxide>=60.5"
 $ 10 : chr [1:4] "root" "alcohol< 9.85" "totalSulfurDioxide< 60.5" "sulphates< 0.575"
 $ 22 : chr [1:5] "root" "alcohol< 9.85" "totalSulfurDioxide< 60.5" "sulphates>=0.575" ...
 (...) lots more

$str(chains[nodeId])
List of 1
 $ 4: chr [1:3] "root" "alcohol< 9.85" "totalSulfurDioxide>=60.5"

$str(unlist(chains[nodeId])[-1])
Named chr [1:2] "alcohol< 9.85" "totalSulfurDioxide>=60.5"
 - attr(*, "names")= chr [1:2] "42" "43"

更新: str 替换为 dput;已添加dput(chains[nodeId])

$ dput(chains)
structure(list(`4` = "alcohol< 9.85", `10` = "alcohol< 9.85", 
    `22` = "alcohol< 9.85", `92` = "alcohol< 9.85", `93` = "alcohol< 9.85", 
    `47` = "alcohol< 9.85", `24` = "alcohol>=9.85", `50` = "alcohol>=9.85", 
    `102` = "alcohol>=9.85", `103` = "alcohol>=9.85", `26` = "alcohol>=9.85", 
    `27` = "alcohol>=9.85", `28` = "alcohol>=9.85", `29` = "alcohol>=9.85", 
    `15` = c("root", "alcohol>=9.85", "alcohol>=11.55", "sulphates>=0.685"
    )), .Names = c("4", "10", "22", "92", "93", "47", "24", "50", 
"102", "103", "26", "27", "28", "29", "15"))

$ dput(chains[nodeId])
structure(list(`15` = c("root", "alcohol>=9.85", "alcohol>=11.55", 
"sulphates>=0.685")), .Names = "15")

$ dput(unlist(chains[nodeId])[-1))
structure(c("alcohol>=9.85", "alcohol>=11.55", "sulphates>=0.685"
), .Names = c("152", "153", "154"))

$ dput(chains[nodeId])
structure(list(`15` = "alcohol>=9.85"), .Names = "15")

我想要实现的是从chains[nodeId]中的向量中删除第一个元素

【问题讨论】:

  • 你能让你的问题重现吗?输出是什么(补一些,或者使用dput),想要的结果是什么?您使用的哪些代码不起作用(您或多或少提供了该代码)?
  • 你到底想做什么?你能举例说明手术前后的列表是什么样的吗?

标签: r list vector


【解决方案1】:

如果chains 是一个列表并且nodeId 是一个字符串,那么chains[nodeId] 将是一个长度为1 的列表。您需要chains[[nodeId]],其中包含该列表的内容。

【讨论】:

  • 谢谢!这是我不知道的双括号。
【解决方案2】:

这是你想要的吗?

# make a list of vectors since no data provided
origlist<-lapply(1:3,function(x)c("a",paste0("b",x),"c"))
names(origlist)<-c("_1","_2","_3")

$`_1`
[1] "a"  "b1" "c" 

$`_2`
[1] "a"  "b2" "c" 

$`_3`
[1] "a"  "b3" "c" 

# remove first item from each as per your example
lapply(origlist, tail, n = -1)

$`_1`
[1] "b1" "c" 

$`_2`
[1] "b2" "c" 

$`_3`
[1] "b3" "c" 

【讨论】:

  • 感谢您的回答,我花了一段时间才理解它,但这确实是一种有趣的方法。我会接受 Richie 的回答,因为这正是我想要的。
猜你喜欢
  • 2014-11-20
  • 2014-12-11
  • 1970-01-01
  • 2022-01-25
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
相关资源
最近更新 更多