0

I try to create a function. But when I change the sequence of it then it create NA values out. Any particular reason to it? Thanks

new<-function(x){
    min2<-NULL
    min1<-NULL
    len<-length(unique(x))
for (i in 1:(len-1)) 
    min2[i]<-sort(x,partial=(len-i+1))[(len-i+1)]
    min1[i]<-sort(x,partial=(len-i))  [(len-i)]
    return((min1))  
}


x<-c(1,11,40,120)

new(x)

[1] 120  40  11




new<-function(x){
    min2<-NULL
    min1<-NULL
    len<-length(unique(x))
for (i in 1:(len-1)) 
    min1[i]<-sort(x,partial=(len-i))  [(len-i)]
    min2[i]<-sort(x,partial=(len-i+1))[(len-i+1)]
    return((min1))  
}


x<-c(1,11,40,120)

new(x)

[1] NA  NA  11

1 Answer 1

3

You forgot curly parentheses around the expression you want to repeat in you for loop:

new<-function(x){
    min2<-NULL
    min1<-NULL
    len<-length(unique(x))
    for (i in 1:(len-1)) {
      min2[i]<-sort(x,partial=(len-i+1))[(len-i+1)]
      min1[i]<-sort(x,partial=(len-i))  [(len-i)] 
    }
    return(min1)  
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Thats very silly of me to forget about the parentheses.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.