Reputation: 508
I have file in R that looks like this:
Sample top bot value
A1 0 10 20
A2 10 20 23
A3 20 25 12
A4 25 30 23
I need to inflate this to increments of top and bottom and divide the value among those
Sample top bot value
A1 0 1 2
A1 1 2 2
A1 2 3 2
A1 3 4 2
A1 4 5 2
A1 5 6 2
...
I guess I have to create a for loop, but no idea how to generate the new data.frame. Its tricky to find something about that, since most questions aim to crunch down data, instead of blowing it up.
Upvotes: 0
Views: 80
Reputation: 81693
You can use lapply
to apply a function to subsets of a data frame:
# Your data frame:
dat <- read.table(text = "Sample top bot value
A1 0 10 20
A2 10 20 23
A3 20 25 12
A4 25 30 23", header = TRUE)
do.call(rbind, lapply(seq(nrow(dat)), function(x) {
tmp <- seq(dat$top[x], dat$bot[x])
top <- head(tmp, -1)
bot <- tmp[-1]
value <- dat$value[x] / length(top)
data.frame(Sample = dat$Sample[x], top, bot, value)
}))
This returns:
Sample top bot value
1 A1 0 1 2.0
2 A1 1 2 2.0
3 A1 2 3 2.0
4 A1 3 4 2.0
5 A1 4 5 2.0
6 A1 5 6 2.0
7 A1 6 7 2.0
8 A1 7 8 2.0
9 A1 8 9 2.0
10 A1 9 10 2.0
11 A2 10 11 2.3
12 A2 11 12 2.3
13 A2 12 13 2.3
14 A2 13 14 2.3
15 A2 14 15 2.3
16 A2 15 16 2.3
17 A2 16 17 2.3
18 A2 17 18 2.3
19 A2 18 19 2.3
20 A2 19 20 2.3
21 A3 20 21 2.4
22 A3 21 22 2.4
23 A3 22 23 2.4
24 A3 23 24 2.4
25 A3 24 25 2.4
26 A4 25 26 4.6
27 A4 26 27 4.6
28 A4 27 28 4.6
29 A4 28 29 4.6
30 A4 29 30 4.6
Upvotes: 4