Try to search your question here, if you can't find : Ask Any Question Now ?

In R loop through one data frame to generate another data frame conditionally with one or more rows for each row in the first data frame

HomeCategory: stackoverflowIn R loop through one data frame to generate another data frame conditionally with one or more rows for each row in the first data frame
Avatarkundan asked 1 month ago

I have a dataset like this:

set.seed(71)
dat <- data.table(region = rep(c('A','B'), each=10),
    place = rep(c('C','D'), 10),
    start = sample.int(5, 20, replace = TRUE),
    end = sample.int(10, 20, replace = TRUE),
    count = sample.int(50, 20, replace = TRUE),
    para1 = rnorm(20,3,1),
    para2 = rnorm(20,4,1))

I would like to loop through this data to conditionally generate another table with the following columns:
region, place, start, end, count, count0
with potentially more than one rows for each row in dat.
in the new table, data for columns region, place, and start will be copied over from dat, and data for columns end, count, and count0 will be generated.

Here are the rules for iterating through each row of dat:

end = end +1
if (count=0) {
  count0=0
} else {
  count0=start*para1 + end*para2
}
if (count0>count) {
  count0=count
}
count = count -count0

I tried to use the combination of for loop, if statement, and mutate but could not get it right.

I expect to get a table like this after going through the first two rows of dat:

region  place   start   end       count         count0
     A      C       2     7  6.01673062    17.98326938
     A      C       2     8           0     6.01673062
     A      D       3     2  5.34392419     7.65607581
     A      D       3     3           0     5.34392419


the first two rows of dat I have are:
region  place   start   end count   para1         para2
     A      C       2     6    24   0.39412969  2.45643
     A      D       3     1    13   0.64372127  2.862456
1 Answers
Best Answer
AvatarJyoti answered 1 month ago
Your Answer

17 + 1 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com