【问题标题】:Adding a new column(group) to a data frame based on the two other data frames基于其他两个数据框向数据框添加新列(组)
【发布时间】:2021-05-12 01:48:54
【问题描述】:

R 新手。我想根据 df2 和 df3 在 df1 中添加一个新列

df1
ind t1 t2 
1 12 0.2
2 NA 0.3
3 9 0.3
4 11 0.4
5 11 0.3
6 10 0.4
7 14 0.3

df2 和 df3 是 df1 的子集

df2
ind t1
1 12
2 NA
3 9
df3
ind t1
4 11
7 14 
8 12

想要的输出

df1 
ind t1 t2 group
1 12 0.2 df2
2 NA 0.3 df2
3 9 0.3 df2
4 11 0.4 df3
5 11 0.3 NA
6 10 0.4 NA
7 14 0.3 df3

是否有使用 for 循环和 if 语句获得所需的输出?

【问题讨论】:

  • 请在R中输入?merge。
  • merge(df1, rbind(df2, df3), all.x = TRUE)

标签: r dataframe


【解决方案1】:

您好,欢迎使用,请提供 dput(),但您可以这样做

library(tidyverse)

df_class <- bind_rows(df2,df3)

df_result <- df_1 %>% 
  left_join(df_class)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-14
    • 2018-01-13
    • 2019-04-04
    • 2023-04-02
    • 2022-12-01
    • 2016-09-11
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多