1

Hi I am new to learning R.

I am running a loop to find out number of man based on their region and value "v" in data frame specified bellow. I would like to save the result of the loop to data frame so that I can work with it. Thank you for your help.

data<-data.frame(x=rep(c("man", "woman"),500),reg=rep(1:5, 200), v=c(seq(100,1,length.out = 500),c(seq(1,100,length.out = 500))))

for (i in seq(0, 100, 10)) {

  print(paste("interval <", i, "-", i+10,">"))
  data %>% 
    filter(data$x == "man" & data$v >= i & data$v <= i +10) %>%   
    group_by(Region = reg) %>% 
    summarize(No_man = n()) %>%
    as.data.frame() %>%
    print()
  if (i+10 > 90) {break}
}
2
  • Have those results stored into another object like so tempdat <- data %>% .... I think this would be the easiest way out of your predicament. Commented Nov 2, 2019 at 23:31
  • Hi, I added the object tempdat in to the loop like you mentioned, but all that is written out to the tempdat object is the last interval (90-100). Commented Nov 20, 2019 at 10:21

1 Answer 1

1

I don't think you need a for loop here -- we can use cut to create the intervals inside a mutate call:

library(dplyr)

res <- 
data %>% 
  filter(v <= 100 & x == "man") %>% 
  mutate(Interval = cut(v, seq(0, 100, 10))) %>% 
  group_by(Region = reg, Interval) %>% 
  tally() %>% 
  ungroup()

head(res)
## A tibble: 6 x 3
#  Region Interval     n
#   <int> <fct>    <int>
#1      1 (0,10]       9
#2      1 (10,20]     10
#3      1 (20,30]     10
#4      1 (30,40]     10
#5      1 (40,50]     10
#6      1 (50,60]     10

Believe this is your expected output.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, that was mighty usefull :), this is much more elegant solution...and it actually works :D compared to mine anyways.
If it helped, feel free to upvote and accept as an answer
Sorry it took some time...answer accepted, as for the upvote...I have less than 15 rep. so it will probably take a while before it shows up for everyone.

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.