【问题标题】:in R: reorder the rows of a dataframe based on those in another table [duplicate]在R中:根据另一个表中的行重新排序数据帧的行[重复]
【发布时间】:2014-10-27 23:43:13
【问题描述】:

我有一张如下表:

tab1 <- as.table(matrix(c(8,6,9,0,8,4,0,12,7,10), ncol = 2, byrow = FALSE, 
   dimnames = list(site = c("beta", "alpha", "gamma", "theta", "delta"),
  count = c("low", "high"))))
> tab1
        count
site    low high
beta    8    4
alpha   6    0
gamma   9   12
theta   0    7
delta   8   10

以及一个将站点名称映射到站点 ID 的 data.frame:

data.frame(site = c("alpha", "beta", "gamma", "delta", "theta"), siteId = c(1102, 3154, 9000, 1101, 1103))
     site siteId
1   alpha   1102
2    beta   3154
3   gamma   9000
4   delta   1101
5   theta   1103

最后,我有一个包含这些 siteID 和其他一些变量的 data.frame:

data.frame(siteId = c(1101, 1102, 1103, 3154, 9000), treatment = c("A", "B", "C", "E", "F"))
  siteId treatment
1   1101         A
2   1102         B
3   1103         C
4   3154         E
5   9000         F

我需要做的是以与 tab1 中的行相同的方式对最后一个数据帧中的列进行排序,因此它应该产生:

  siteId treatment
1   3154         E
2   1102         B
3   9000         F
4   1003         C
5   1001         A

如何在不进行复杂循环的情况下做到这一点?实际的数据集非常大,因此循环会花费比我想要的更多的时间。

【问题讨论】:

  • 感谢您找到该相关问题,它比我的稍微简单,但确实非常相似。

标签: r


【解决方案1】:

您可以通过matching 来自不同数据帧的 ID 来做到这一点。顺便说一句,我将数据框a 中的epsilon 更改为theta,因为tab1 中没有epsilon。

tab1 <- as.table(matrix(c(8,6,9,0,8,4,0,12,7,10), ncol = 2, byrow = FALSE, 
                                                dimnames = list(site = c("beta", "alpha", "gamma", "theta", "delta"),
                                                                                count = c("low", "high"))))


a = data.frame(site = c("alpha", "beta", "gamma", "delta", "theta"), siteId = c(1102, 3154, 9000, 1101, 1103))
b = data.frame(siteId = c(1101, 1102, 1103, 3154, 9000), treatment = c("A", "B", "C", "E", "F"))

# put a in the order of tab1
a = a[match(a$site,rownames(tab1)),]

# put b in order of a
b = b[match(a$siteId, b$siteId),]

> b
#  siteId treatment
#4   3154         E
#2   1102         B
#5   9000         F
#3   1103         C
#1   1101         A

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 2014-12-20
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    相关资源
    最近更新 更多