简体   繁体   English

从R中的data.frame生成数据行

[英]Generate data rows from data.frame in R

I have file in R that looks like this: 我在R中有一个看起来像这样的文件:

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. 我想我必须创建一个for循环,但不知道如何生成新的data.frame。 Its tricky to find something about that, since most questions aim to crunch down data, instead of blowing it up. 很难找到答案,因为大多数问题的目的是粉碎数据,而不是炸毁数据。

You can use lapply to apply a function to subsets of a data frame: 您可以使用lapply将函数应用于数据框的子集:

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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