Reputation: 11
I want to be able to search or filter a column and if it meets certain parameters, return the value in another column (but at a different point).
So for example,
L <- matrix(rnorm(500, mean=50, sd=4), nrow=100, ncol=5, byrow=FALSE)
L <-as.data.frame(L)
colnames(L)<-c("1","2","3","4","5")
If L[,"1"] >= 58
I want to print the value of the value in L[,"4"]
that is 5 rows lower.
So if L[1,1]
had a value of 60, I want the value of L[6,4]
and do this for all values in L[,"1"]
that meet these parameters. Preferably with a printout that gives a clear indication of multiple pairing values (ie the corresponding coordinates).
Help starting this would be greatly appreciated and obviously solutions are helpful as well. I know how to filter and make a subset of a data frame consisting of certain values, but I have no idea how to pull objects at a different portion like in this problem.
Upvotes: 0
Views: 463
Reputation: 5537
Well, as for help getting started, the which
function will be helpful. It returns the indices that meet a certain criteria - so to see all rows for which column "1" is greater than 58, you can use:
matched.indices <- which(L[,"1"] > 58)
To then find all the indices that are 5 rows lower, we can simply add 5:
shifted.indices <- matched.indices + 5
From here, you can print out the pairs of values and coordinates however you want to. One way would be as follows:
len <- length(matched.indices)
cat(paste(rep("[",len), matched.indices, rep(",1],", len), # 1st coordinate
rep("[",len), shifted.indices, rep(",4] = ", len), # 2nd coordinate
L[matched.indices, "1"], # 1st value
rep(",", len),
L[shifted.indices, "4"], # 2nd value
sep=""),sep="\n")
The output will look like this:
[4,1],[9,4] = 58.9223792285318,48.5241852967192
[70,1],[75,4] = 58.5015984791419,55.3071097158975
[76,1],[81,4] = 61.7996739529131,51.6725968541657
[85,1],[90,4] = 58.0881601753751,40.2410431328713
[92,1],[97,4] = 58.1622310810397,50.6118549434608
[96,1],[101,4] = 58.4433975051732,NA
As I said, it's just a start. Specifically, you did not mention what to do with the last 5 rows; my solution will just print NA for those values (as with the last row above). If you want to clarify that point, I'll update the answer accordingly.
Upvotes: 1