Home > Software design >  How do I access each element inside vapply or any apply function in R?
How do I access each element inside vapply or any apply function in R?

Time:11-23


g <- c(1,2,3,4)
vapply(g, function(x) {

length(x) # This prints out a value of 1. 

# Is there code I can write that will allow me to uniquely access just the second element in this vector?



})

I am looking to use vapply specifically, but would like to know how I can access just a single element (any index I want) in the vector that vapply is being acted on. How can I achieve this?

CodePudding user response:

The R work around for something like this is usually:

g <- c(1,2,3,4)

vapply(seq_along(g), function(i) {
## i is your index number 
## g[i] is the ith element in g
}, double(1))

CodePudding user response:

When I have a list or vector of things and I want to vapply (or lapply or ...) on one or more of them (technically zero-or-more), I use a "subset-assignment" technique:

g <- c(1, 2, 3, 4)
ind <- 2
### could also be:
# ind <- c(2, 4)
# ind <- c(TRUE, FALSE, TRUE, TRUE) # logical variant
# ind <- c()                        # empty
g[ind] <- lapply(g[ind], function(x) ...)

This does not need to reassign back into g, it could be a new vector:

newg <- lapply(g[ind], function(x) ...)

where in this case length(newg) would be the same as length(ind) (or sum(ind) if using the logical variant).

  •  Tags:  
  • r
  • Related