How to delete an element at a time from a vector w

2020-02-15 04:05发布

I have a vector x containing 5 elements.

x <- (1,2,3,4,5)

I would want to delete one element at each iteration and retain other elements in the vector.(as shown below)

x <- (2,3,4,5)     #vector after first iteration 

x <- (1,3,4,5)     #vector after second iteration 

x <- (1,2,4,5)     #vector after third iteration 

x <- (1,2,3,5)     #vector after fourth iteration 

and also, is it possible to store these new vectors in a list? is there a way to extend this to multiple vectors?

标签: r vector row
4条回答
狗以群分
2楼-- · 2020-02-15 04:45
drop_n <- function(n, x) x[-n]
lapply(1:5, drop_n, x)
查看更多
Viruses.
3楼-- · 2020-02-15 04:48

Here you have a way to get what you want. You only need to change the parameter n to make it more general

    # Generate a list
      L <- list()
    # Define the number of elements
      n <- 5
    # Define the values
      values <- 1:n

    # Complete the list
      for (i in 1:n){
        L[[i]] <- values[-i]
      }
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-15 04:51

You could use combn:

combn(5,4)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    2
[2,]    2    2    2    3    3
[3,]    3    3    4    4    4
[4,]    4    5    5    5    5

To get the data as a list:

as.list(data.frame(combn(5,4)))

To use this on multiple vectors or a matrix, first transform it into a data.frame, to make it easier for lapply to go over the length (columns) of the data.frame. Then you can use lapply with combn like so:

mat <- data.frame(matrix(1:10,5))
lapply(mat, function(x) combn(x,length(x)-1))

$X1
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    2
[2,]    2    2    2    3    3
[3,]    3    3    4    4    4
[4,]    4    5    5    5    5

$X2
     [,1] [,2] [,3] [,4] [,5]
[1,]    6    6    6    6    7
[2,]    7    7    7    8    8
[3,]    8    8    9    9    9
[4,]    9   10   10   10   10
查看更多
来,给爷笑一个
5楼-- · 2020-02-15 04:51

We can do

lapply(seq_along(x), function(i) x[-i])
查看更多
登录 后发表回答