user3780691
user3780691

Reputation: 83

Loop over list of R objects and change each object

I want to make a list of objects of a particular class in R, go through the list, and change each object according to some criterion. For example:

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
  }
}

The expression get(AllDucks[i])$cap <- 1 gives the error message

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

How can I pick an object from a list of objects and change some of its attributes?

Upvotes: 1

Views: 85

Answers (2)

MrFlick
MrFlick

Reputation: 206242

To reassign into the current environment, you could do

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

Upvotes: 0

Roland
Roland

Reputation: 132706

Why don't your ducks swim nicely in a pond? You should give them a nice habitat to begin with, but you can also catch them from the wild:

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"

Upvotes: 1

Related Questions