计算R中长度不均匀的表格

时间:2016-09-29 08:56:37

标签: r

我必须在R

中找到数据表
a =   Duration (-10,0] (0,0.25] (0.25,0.5] (0.5,10]
1        2       0        0          0        2
2        3       0        0         10        3
3        4       0       51         25        0
4        5      19      129         14        0
5        6      60      137          1        0
6        7      31       62         15        5
7        8       7       11          7        0

b =   Duration (-10,0] (0,0.25] (0.25,0.5] (0.5,10]
1        1       0        0          1      266
2        2       1        0         47      335
3        3       1       26        415      142
4        4       3      965        508        5
5        5     145     2535        103        0
6        6     939     2239         15        6
7        7     420      613         86       34
8        8      46       84         36       16

我想通过匹配持续时间来计算b / a。我虽然有一些像ifelse()但它不起作用。有人可以帮帮我吗? 非常感谢

2 个答案:

答案 0 :(得分:1)

匹配b的顺序和选择a(在我的例子中y与x)。然后做数学。

x <- data.frame(duration = 2:8, v = rnorm(7))

y <- data.frame(duration = 8:1, v = rnorm(8))
m <- match(y$duration, x$duration)

ym <- y[m[!is.na(m)],]

x$v/ym$v

当x包含不在y,btw。

中的项目时,它不起作用

答案 1 :(得分:0)

您想要以下内容:

a <- a[-1]
b <- b[-1]

a <- a[order(a$Duration),]
b <- b[order(b$Duration),]
durations <- intersect(a$Duration, b$Duration)
b[b$Duration %in% durations,] / a[a$Duration %in% durations,]

  Duration   (-10,0]  (0,0.25] (0.25,0.5]  (0.5,10]
2        1       Inf       NaN        Inf 167.50000
3        1       Inf       Inf  41.500000  47.33333
4        1       Inf 18.921569  20.320000       Inf
5        1  7.631579 19.651163   7.357143       NaN
6        1 15.650000 16.343066  15.000000       Inf
7        1 13.548387  9.887097   5.733333   6.80000
8        1  6.571429  7.636364   5.142857       Inf

您可能希望用其他东西替换NaN和Inf值。