0

here the input data and my expectations (y).

# input:
mydf <- data.frame(matrix(1:10, ncol = 2))
x=c(1.5, 2.8, 4.1)
y=c(0, 0, 0)
mydf
x
y

# code
for (i in 1:(length(x))
    for (j in 2:(dim(mydf)[1])
    {{
        if (x[i])>mydf[(j-1),1]) & (x[i])<mydf[j,1]) 
            {y[i]<-mydf[(j-1),2]} 
        else {y[i]<-9999999999}
    }}
y

expectation for y: 6,7,9. I do not understand the error.

1
  • 1
    You need to place the opening and closing brackets in the right position. That is, for(condition){dostuff}. The same goes for if-statements. And for-loops are not really needed here. Commented Nov 3, 2015 at 16:50

1 Answer 1

1

Here is a code that will work and give your expected output :

for (i in 1:length(x)) {
    for (j in 2:nrow(mydf)) {
        if (mydf[j-1,1] < x[i] & x[i] < mydf[j,1]) {
            y[i] <- mydf[j-1,2]    
            break
        } else {y[i]<-9999999999}
    }
}

y

[1] 6 7 9

You need to add the break otherwise j will keep looping and return 9999999999.

A more elegant option would be this :

x=c(1.5, 2.8, 4.1,11)
mydf[nrow(mydf),2]<-999999 # y can't be equal to the lower right cell, so I transform it
y<-mydf[findInterval(x,mydf[,1]),2]
y

y
[1]      6      7      9 999999

An other solution would be this (it is best if some values will return 9999) :

x<-c(-3,1.5, 2.8, 4.1,11)
temp<-sapply(x,function(z){z>mydf[,1]&z<mydf[-1,1]})
temp2<-sapply(seq_along(x),function(z){match(TRUE,temp[,z])})
y<-mydf[temp2,2]
y[is.na(y)]<-9999
y

[1] 9999    6    7    9 9999
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.