user2560984
user2560984

Reputation: 381

How do I subset a list in R by selecting all elements in a list except for one value?

So basically I have a list called "parameters" with values (x1, x2, ... , xj). I want to, through a for loop, subset this list, but each time leave out one element. So for example I want the first subset (through the first iteration of the for loop) to be (x2, x3, ..., xj), and the next to be (x1, x3, ..., xj) and so on, until the last subset which would be (x1, x2, ... , xj-1). How do I do this?

Upvotes: 7

Views: 13419

Answers (5)

patternizer
patternizer

Reputation: 11

If I understand correctly, something like this loop for constructing formulae by permuting a list of variables into a response variable and predictor equations might be helpful to you:

all_variables <- c("x1", "x2", "x3", "x4", "x5")
for (i in 1:length(all_variables)){
  combo <- all_variables[-i]
  formula <- as.formula(paste(all_variables[i], "~", paste(combo, collapse = " + ")))
  #
  # use "formula" here
  # e.g.
  # print(formula)
  #
}

Hope this helps. Best regards,

Upvotes: 0

maycca
maycca

Reputation: 4090

You can subset the element from the list by indicating they order in the list.

To select the items 1 and 3 from a list

my.list[c(1,3))]

Try this:

# create a dummy list of data frames
d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
d3 <- data.frame(y1=c(3,2,1),y2=c(9,8,7))
my.list <- list(d1, d2, d3)

# get the items 1 and 3
my.list[c(1,3)]

# get the all element except of the first one
my.list[c(-1)]

Upvotes: 1

cryo111
cryo111

Reputation: 4474

Just in case you want to use the data for a leave-one-out jackknife, here a quick pointer to the bootstrap package and a short example

library(bootstrap)
vec_list=list()
jackknife(rnorm(10,0,1),function(x) {vec_list[[length(vec_list)+1]]<<-x;mean(x)})
vec_list[1:10]

Upvotes: 0

Jilber Urbina
Jilber Urbina

Reputation: 61214

this could be useful

> Vector <- paste("x", 1:6, sep="")
> lapply(1:length(Vector), function(i) Vector[-i])

Upvotes: 9

Thomas
Thomas

Reputation: 44555

I'm assuming by "list" you mean vector. If so:

parameters <- rnorm(100)
y <- matrix(nrow=length(parameters)-1,ncol=length(parameters))
for(i in 1:length(parameters))
    y[,i] <- parameters[-i]

If by "list", you actually mean a list, the code is basically the same, but just do parameters <- unlist(parameters) first.

Upvotes: 2

Related Questions