0

i Have a Df:abc as below

Sr|VALUE
a |85
b |120
c |145
d |225
e |100
f |325
g |410

I am writing below code to create a count for each record such that its 0 for VALUE<100,1 for VALUE between[100,200),2 for VALUE>=200

Stepdif<-100

abc = within(abc, {                   
  Count = ifelse(abc$VALUE>=Stepdif & abc$VALUE<2*Stepdif,1,ifelse(abc$VALUE>=2*Stepdif ,2,0))
  })

to give result as

Sr|VALUE|Count
a |85   |0
b |120  |1
c |145  |1
d |225  |2
e |100  |1
f |325  |2
g |410  |2

Now i want a code using which i can define count for each duration of 100. I dont want to write code as such

Count = ifelse(abc$VALUE>=Stepdif & abc$VALUE<2*Stepdif,1,ifelse(abc$VALUE>=2*Stepdif & abc$VALUE<3*Stepdif,2,ifelse(abc$VALUE>=3*Stepdif & abc$VALUE<4**Stepdif,3,ifelse(abc$VALUE>=4*Stepdif ,4,0))))

Rather i want to make it dynamic so that if i change the no of iteration from 4 to 6 , i dont have to rewrite the code again.

expected result
Sr|VALUE|Count
a |85   |0
b |120  |1
c |145  |1
d |225  |2
e |100  |1
f |325  |3
g |410  |4
2
  • 1
    How about using cut i.e. with(abc, cut(VALUE, breaks = c(-Inf, Stepdif *(1:2), Inf))) Commented Aug 9, 2017 at 9:03
  • 1
    Look into findInterval() in the base package. Commented Aug 9, 2017 at 9:03

1 Answer 1

1

hope this will be of help:

   funfun=function(x,n){n=1:n*100; findInterval(x,n)}

  funfun(k$VALUE,2)
  [1] 0 1 1 2 1 2 2
  funfun(k$VALUE,4)
  [1] 0 1 1 2 1 3 4
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.