简体   繁体   English

如何通过选择列表中除一个值之外的所有元素来对R中的列表进行子集化?

[英]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). 所以基本上我有一个名为“参数”的列表,其值为(x1,x2,...,xj)。 I want to, through a for loop, subset this list, but each time leave out one element. 我想通过for循环子集这个列表,但每次都省略一个元素。 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). 所以例如我希望第一个子集(通过for循环的第一次迭代)是(x2,x3,...,xj),然后是(x1,x3,...,xj),所以on,直到最后一个子集(x1,x2,...,xj-1)。 How do I do this? 我该怎么做呢?

this could be useful 这可能很有用

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

I'm assuming by "list" you mean vector . 我假设“列表”你的意思是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. 如果通过“list”,你实际上是指一个list ,代码基本相同,但只是先做parameters <- unlist(parameters)

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 从列表中选择项目1和3

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)]

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 如果您想将数据用于留一式换刀,这里有一个指向bootstrap包的快速指针和一个简短示例

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM