The best way to learn this is to experiment with it since it's an interactive environment, and it's easy to create dummy data.
With regards to making comparisons in neighboring rows, the easiest thing to do is to use the -
operator (which means "exclude this index") to eliminate the first and last row, as in this example:
a <- 1:10
a[5] <- 0
a[-1] > a[-length(a)] # compare each row with the preceding value
If you want to do an if
statement, you have two options:
1) The if
command only evaluates one value, so you need to ensure that it evaluates to TRUE/FALSE (e.g. use the all or any functions):
if(all(a[-1] > a[-length(a)])) {
print("each row is incrementing")
} else {
print(paste("the",which(c(FALSE, a[-1] <= a[-length(a)])),"th row isn't incrementing"))
}
2) You can do a vectorized if statement with the ifelse
function. See help("ifelse")
for more details. Here's an example:
ifelse(a[-1] > a[-length(a)], 1, 0)