This question already has answers here:
Count observations greater than a particular value [duplicate]
(3 answers)
Closed 2 years ago.
I have a list
x <- c(1,2,3,4,5)
How do I count how many elements are over 3. So the output would be 2.
Take advantage of the fact logical are represented by 1 and 0
sum(1:5 > 3)
You can do like this:
x <- list(1, 2, 3, 4, 5)
sum( x > 3 )
#Output: [1] 2
Related
This question already has answers here:
Remove rows with all or some NAs (missing values) in data.frame
(18 answers)
Closed 3 years ago.
I have two vectors, say A and B
A <- c(1, 2, 3, 4, 5)
B <- c(6, NA, 8, 9, NA)
I would like to exclude elements in A corresponding to the elements of B which comprise NAs.
So, I am in need of an automatic way to remove indices 2 and 5 from both A and B, so that the length of both vectors is the same.
Use is.na
A[!is.na(B)]
#[1] 1 3 4
B[!is.na(B)]
#[1] 6 8 9
Something like
na.omit(cbind(A,B))
This question already has answers here:
Numbering rows within groups in a data frame
(10 answers)
Closed 5 years ago.
If I have a vector of numbers in R.
numbers <- c(1,1, 2,2,2, 3,3, 4,4,4,4, 1)
I want to return a vector that provides the number of times that value has occurred cumulatively along the vector. I.e.
results <- c(1,2, 1,2,3, 1,2, 1,2,3,4, 3)
We can use ave and apply the seq_along by grouping with the 'numbers' vector
ave(numbers, numbers, FUN = seq_along)
#[1] 1 2 1 2 3 1 2 1 2 3 4 3
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 combine all rows into a single row in R? [closed]
(2 answers)
Closed 6 years ago.
Got a basic R for-loop matrix question:
My matrix looks something like this:
2 4 3
1 5 7
All I want is to print these elements row wise and not column wise. The answer should be like 2 4 3 1 5 7. All I try I get the result column wise i.e `2 1 4 5 3 7. Since m just beginning R wondering if it can be done by just for-loop which loops column wise and not row-wise
m <- matrix(c(2, 4, 3, 1, 5, 7), 2, 3, byrow=T)
as.vector(m)
or
c(m[1, 1:3], m[2, 1:3])
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