【问题标题】:Extract Values from one table based on columns in another table根据另一个表中的列从一个表中提取值
【发布时间】:2018-04-24 14:03:23
【问题描述】:

我有两个数据框。第一个(df1)看起来像:

Item       Col1        Col2        Col3         
 A         Food        Fruit       Apple        
 B         Food        Veggie      NA
 C         xxx          yyy        zzz   

第二个表(df2)看起来像:

 Name        Number
Apple         Col3
Veggie        Col2

我想获得如下决赛桌:

Item        Name        Number
 A          Apple        Col3
 B          Veggie       Col2

我尝试使用 for 循环:

    for (i in 1:nrow(df2)){ 
        new_df <- subset(df1, df2[i,1] %in% df1$df2[,2])
        print(new_df)
}

我知道我的代码的语法是错误的。如果有人对我应该做什么有任何想法,请告诉我。谢谢!

【问题讨论】:

  • df1[cbind(1:nrow(df1),match(df2$Number,names(df1)))]
  • 如果你有 Name = "Food" 和 Number = "Col1",那么最终表中“Item”的正确值就不清楚了......你想要 A 和 B 吗?

标签: r for-loop dataframe data.table


【解决方案1】:

我们可以重塑第一个数据框,然后通过第二个数据框对其进行过滤。 df3 是最终输出。

library(tidyverse)

df3 <- df1 %>%
  gather(Number, Name, -Item) %>%
  semi_join(df2, by = c("Name", "Number")) %>%
  select(Item, Name, Number) %>%
  arrange(Item)
df3
#   Item   Name Number
# 1    A  Apple   Col3
# 2    B Veggie   Col2

数据

df1 <- read.table(text = "Item       Col1        Col2        Col3         
 A         Food        Fruit       Apple        
 B         Food        Veggie      NA
 C         xxx          yyy        zzz ",
                  header = TRUE, stringsAsFactors = FALSE)


df2 <- read.table(text = " Name        Number
Apple         Col3
Veggie        Col2",
                  header = TRUE, stringsAsFactors = FALSE)

【讨论】:

  • 将其转换为 data.table 将是 setDT(df2)[melt(setDT(df1), "Item"), Item := i.Item, on = .(Name = value)]
  • @DavidArenburg 感谢data.table 解决方案。
  • 感谢您的解决方案!这绝对帮助了我!
【解决方案2】:

使用基础 R 提取而不是合并:

cbind(df1[1],Name=df1[cbind(1:nrow(df1),match(df2$Number,names(df1)))],df2[2])
  Item   Name Number
1    A  Apple   Col3
2    B Veggie   Col2

【讨论】:

  • 感谢 Onyambu 的帮助!真的很感激!
【解决方案3】:

如果你想用循环来做,你可以这样做:

数据

df1 = data.frame(Item=c("A","B"), Col1 = "Food", Col2 = c("Fruit", "Veggie"), 
  Col3 = c("Apple",NA), stringsAsFactors = F)
df2 = data.frame(Name  = c("Apple", "Veggie"), Number = c("Col3", "Col2"),
  stringsAsFactors = F)

循环解决方案

new_df = df2
for(i in 1:nrow(new_df)){
  new_df$Item[i] = df1[which(df1[[df2$Number[i]]] == df2$Name[i]),"Item"]
}
new_df

【讨论】:

    猜你喜欢
    • 2018-06-20
    • 2022-06-24
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    相关资源
    最近更新 更多