简体   繁体   中英

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 data frame 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

and the result should reflect like

b
1
2
3
4
5
6
7
8
9
10

Any leads will be appreciated

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

Did you want all the values of a less than 10 then b = 1:10 , if all the values of a less than 14 then b = 11:14 and if all the value of a less than 29 then b = 15:29 : Please check the code below for details

df <- data.frame(a = c(1,5,7,9))

if (sum(df$a < 10) == nrow(df)) {
b = data.frame(1:10)
} else if (sum(df$a < 14) == nrow(df)) {
b = data.frame(11:14)
} else if (sum(df$a < 29) == nrow(df)) {
b = data.frame(15:29)
}

Out of above code is:

> b
   X1.10
1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10    10

Hope this will help you, otherwise let me know your exact requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM