【问题标题】:How to make new column in data frame using x,y index numbers of a second lookup dataframe?如何使用第二个查找数据框的 x,y 索引号在数据框中创建新列?
【发布时间】:2019-09-17 21:25:44
【问题描述】:

我有两个数据框。第一个是查找数据框,其中包含许多变量。示例:

Lookup <- data.frame(A = 1:7,B = 8:14)

  A  B
1 1  8
2 2  9
3 3 10
4 4 11
5 5 12
6 6 13
7 7 14

第二个包含模型的输出,其中两列引用查找数据框的索引。示例

Model <- data.frame(Column = c(2,2), Row = c(7,4))

  Column Row
1      2   7
2      2   4

作为参考,我想要基于查找数据帧中的索引的模型数据帧的第三列。示例:

  Column Row Lookup
1      2   7     14
2      2   4     11

我打算在我的查找列中添加以下内容:

Model$Lookup <- Lookup[Model$Row,Model$Column]

但是,当我运行此代码时,有 95% 的时间会向模型数据框中添加比我预期的多得多的列。我怀疑我在模型数据框中添加了与数据行一样多的列 - 它们包含的数据来自 Lookup 数据框,但顺序混乱。

另外 5% 的时间我只得到一列,但 50% 的答案是正确的。其余数据似乎是一些正确答案的副本。

这可能是基本的,但任何人的任何帮助或想法都将不胜感激!

【问题讨论】:

    标签: r dataframe indexing coordinates lookup


    【解决方案1】:

    我们可以通过matrix使用行/列索引

    Model$Lookup <- Lookup[as.matrix(Model[2:1])]
    

    【讨论】:

    • transform(Model, Lookup = Lookup[cbind(Row, Column)])
    • 我是个初学者。你能解释一下为什么矩阵在这种情况下有效吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2021-11-30
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2021-12-01
    • 2020-10-08
    相关资源
    最近更新 更多