Search code examples
rvariable-assignmentassignment-operator

What's the difference between () and [] in R


x <- c(2,4,6,8,10)

What are the outcomes of the following,

sum(x>5) 
sum(x[x>5])

Could anyone tell me what it exactly it means, I'm new to R Programming.


Solution

  • x>5 returns FALSE FALSE TRUE TRUE TRUE the sum of which is 3 because of the 3 TRUEs. It is telling you whether the condition is met for each value of x (x[i]>5?) and summing the responses.

    x[x>5] subsets x for each value that is greater than 5, returning 6, 8 and 10, the sum of which is 24.