Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

r - How to delete an element at a time from a vector while retaining the others?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...