List and arrays
Title
Question
How to discard alternate numbers from an array and resize the length of an array using R?
R Lists-and-its-Operations 02-03 min 20-30 sec
Answers:
Let's say you have an array A as follows -
A<-c(1,2,3,4,5,6)
Suppose you want to keep only the elements at the odd places then you may create a sequence as follows -
seq(1, length(A), 2)
The sequence will start from 1 to the length of array A by skipping one element or taking the alternate element only.
Now to keep only the elements at the odd places then use the following command -
A <- A[seq(1, length(A), 2)]
For even elements start the sequence from '2' instead of '1' as follows -
A <- A[seq(2, length(A), 2)]
We can do its simply by removing those indices. Here is an example,
a=c(1:20)
b=seq(1,length(a),by=2)
a[-b]
Let say array A = 1,2,3,4,5,6,7 and I want to discard the element 1,2,4. How to discard the same and resize the array?
So, here we want to remove indices 1, 2, 4. You may use B= A[-c(1,2,4)] , then B is resized array.
Login to add comment
Login to add comment