【问题标题】:Reference column name from another table to insert value from shared ID从另一个表中引用列名以插入来自共享 ID 的值
【发布时间】:2021-10-27 15:45:52
【问题描述】:

我正在尝试根据我的主数据帧 (df1$reference) 中的列名列引用另一个数据帧 (df2) 中的列,以返回 ID 和列名在新列 (df1) 中匹配的确切值$new_col)。这是我的数据和预期结果的简化示例:

我尝试了 rbind,但由于行数/列数的不同而出错。我也尝试了 bind_rows/bind_cols,但很难只加入引用的数据(我想避免大连接,因为我的真实数据有更多列)。我觉得索引能够做到这一点,但我不熟悉简单任务之外的索引。我愿意接受任何和所有建议/方法!

【问题讨论】:

  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example。图片不是共享数据/代码的正确方式。

标签: r indexing dplyr rbind


【解决方案1】:

我们可能会使用row/column 索引

DF1$new_col <- DF2[-1][cbind(seq_len(nrow(DF1)), 
        match(DF1$reference, names(DF2)[-1]))]

-输出

> DF1
  ID value reference new_col
1  1     4      colD      no
2  2     5      colD      no
3  3     6      colE      no

数据


DF1 <- structure(list(ID = 1:3, value = 4:6, reference = c("colD", "colD", 
"colE")), class = "data.frame", row.names = c(NA, -3L))

DF2 <- structure(list(ID = 1:3, colD = c("no", "no", "yes"), colE = c("yes", 
"no", "no"), colF = c("no", "yes", "no")), 
class = "data.frame", row.names = c(NA, 
-3L))

【讨论】:

  • 这很有效,非常感谢您的帮助!
【解决方案2】:

也许是这样的?

library(dplyr)
left_join(DF1, DF2, by="ID") %>% 
  mutate(New_col = case_when(reference=="colD" ~ colD,
                             reference=="colE" ~ colE,
                             reference=="colF" ~ colF)) %>% 
  select(ID, value, reference, New_col)
  ID value reference New_col
1  1     4      colD      no
2  2     5      colD      no
3  3     6      colE      no

【讨论】:

    猜你喜欢
    • 2013-03-10
    • 2015-11-19
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2014-06-30
    • 1970-01-01
    相关资源
    最近更新 更多