循环遍历R对象列表并更改每个对象

时间:2014-06-26 19:17:03

标签: r loops object

我想在R中创建特定类的对象列表,浏览列表,并根据某些标准更改每个对象。例如:

Duck <- function(grade,cap) {
  res <- structure(list(grade=grade,cap=cap),class="Duck")
  return(res)
}

Kwik <- Duck(5,0)
Kwek <- Duck(7,0)
Kwak <- Duck(9,0)

# Select all Ducks from the workspace
AllDucks <- Filter( function(x) 'Duck' %in% class( get(x) ), ls() )

# Give each Duck with a grade higher than 5 a cap (i.e. cap is set to 1)
for(i in 1:length(AllDucks)) {
  if(get(AllDucks[i])$grade > 5) {
    get(AllDucks[i])$cap <- 1
  }
}

表达式get(AllDucks[i])$cap <- 1给出错误消息

Error in get(AllDucks[i])$cap <- 1 : could not find function "get<-"

如何从对象列表中选择对象并更改其某些属性?

2 个答案:

答案 0 :(得分:1)

为什么你的鸭子在池塘里游得不好?你应该给他们一个很好的栖息地开始,但你也可以从野外捕捉它们:

pond <- mget(AllDucks)
pond <- lapply(pond, function(x) {
  if (x$grade > 5) x$cap <- 1
  x
})

pond$Kwek
# $grade
# [1] 7
# 
# $cap
# [1] 1
# 
# attr(,"class")
# [1] "Duck"

答案 1 :(得分:0)

要重新分配到当前环境,您可以

mapply(assign, AllDucks, lapply(mget(AllDucks), function(x) {x$cap<-1; x}), 
    MoreArgs =list(envir = environment()))