R Vij R Vij - 4 months ago 6
R Question

writing a for loop in R for a special case

If some data frame which contains values like

a
1
5
7
9


data frame b needs to be extracted from a like

If a is less than equals to 10 than b is 1:10
If a is less than equals to 14 than b is 11:14
If a is less than equals to 29 than b is 15:29


result should reflect like

b
1
2
3
4
5
6
7
8
9
10


Any leads will be appreciated

Answer

We can try

f1 <- function(x){
       v1 <- max(x)
       v2 <- if(v1 < 10) 1:10 else if(v1 < 14) 11:14 else 15:29 
       data.frame(b = v2)
}

f1(df1$a)
#    b
#1   1
#2   2
#3   3
#4   4
#5   5
#6   6
#7   7
#8   8
#9   9
#10 10