我有两个数据框。第一个(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)
}
我知道我的代码语法错误。如果有人对我该怎么做有任何想法,请告诉我。谢谢!
答案 0 :(得分:2)
我们可以重塑第一个数据帧,然后通过第二个数据帧对其进行过滤。 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)
答案 1 :(得分:1)
如果你想用循环来做,你可以这样做:
数据
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
答案 2 :(得分:1)
使用基础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