Subsetting and Indexing in For Loop in R -


i trying collect n number of smallest values in dataset sorted rank.

here code:

testscript <- function(num) {     df <- data.frame(state = paste0("state",sort(rep(1:2,10))),                      city = rep(paste0("city",rep(1:10,2))),                      value = runif(n=20))     vec <- null     df$rank <- ave(df$value, df$state, fun=rank)     (i in 1:num) {          vec[i] <- df[df$rank==[i],]     } } 

the argument num number of smallest values want collect.

when run function, following error:

    error: unexpected '[' in:     "for (i in 1:num) {           vec[i] <- df[df$rank==[" 

if wanted n smallest values in dataset sorted rank, can order , head functions -- no need for loop:

num <- 10 head(df[order(df$rank),], num) #     state   city        value rank # 7  state1  city7 0.1075155728    1 # 19 state2  city9 0.0008769566    1 # 5  state1  city5 0.2829263743    2 # 17 state2  city7 0.0407836910    2 # 6  state1  city6 0.4697333111    3 # 14 state2  city4 0.1197360896    3 # 3  state1  city3 0.4853360290    4 # 11 state2  city1 0.1766399497    4 # 10 state1 city10 0.5803764823    5 # 13 state2  city3 0.3109590847    5 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -