This question already has answers here:
How to tell what is in one vector and not another?
(6 answers)
Closed 5 years ago.
I try to do this in R:(for example)
let x = c(1,2,3,4,5,6,7,8) and y=c(1,2,8)
So
x[x!=y] = numeric(0) ????
I want to get as a result 3,4,5,6,7
Is there a practical way to do this?
Thanks
Use value matching %in% and remove the elements of x that are present in y
x[-which(x %in% y)]
#[1] 3 4 5 6 7
Related
This question already has answers here:
What does the diff() function in R do? [closed]
(2 answers)
Closed 5 months ago.
I dont know what´s the posible way of creating a new vector from a previous one by subtraction
of the second element to the first one and doing it for all the values of the vector, by
applying Xi-X(i-1)
Use diff
> x <- c(5,2,3,4)
> diff(x)
[1] -3 1 1
This question already has answers here:
which.max ties method in R
(4 answers)
Closed 2 years ago.
I have the problem, now you see that:
x<-c(1,2,3,6,4,5,6)
y=(which.max(x))
print(y)
*The result is 4 because it is the position of element 6 (max value). But I want the result returned is 4 and 7.
How can I do that?
Try the below:
which(x==max(x))
[1] 4 7
If you have potential NA values, use
which(x==max(x, na.rm=T))
This question already has answers here:
Check to see if a value is within a range?
(7 answers)
Closed 5 years ago.
I'm starting to learn R, as it's needed for work. I have never done statistical work, so I'm a bit lost.
I'm looking to get the value of x between two numbers.
So, for example, the range is 3:7 I need to print 4,5,6
I have tried
x <- 3:7
x[x>3 && x<7]
and
x <- 3
v <- 7
cbind(x, findInterval(x, v))
Any advice/guidelines
An option is between from data.table
x[data.table::between(x, 3, 7, incbounds = FALSE)]
#[1] 4 5 6
This question already has answers here:
How to randomize a vector
(2 answers)
Closed 6 years ago.
Supposing I have the vector
x <- c(1,2,3,4,5,6)
Is there any way I could randomly mix its elements?
Or create a vector which would have integer elements from 1 to 6 which do not repeat?
We need sample to do that
sample(x)
If it needs to be repeated, use the replicated
replicate(3, sample(x))
This question already has answers here:
Alternate, interweave or interlace two vectors
(2 answers)
Closed 8 years ago.
How can I concatenate two vectors to get a vector with values alternatively from the first and second one?
Input
a<- c(1,2,3)
b<- c(4,5,6)
Output
c(1,4,2,5,3,6)
This is one way
> as.numeric(t(matrix(c(a,b), ncol = 2)))
[1] 1 4 2 5 3 6