【发布时间】:2015-04-21 13:46:41
【问题描述】:
我有一个数据集data1如下
Group Code
Blue 1333
Blue 4444
Blue 9876
Blue 8785
Red 3145
Red 8756
Red 9745
Red 8754
第二个数据集data2如下
Id Description
1333 Sea Weed
4444 Honey Roasted Peanut
8754 Green Tea
8756 Potato Chips
3145 Strawberry Grahams
8787 Arizona Ice Tea
我正在尝试在我的第二个 Dataset 中创建第三列,data2 存储
1 - If the code is from blue Group in Data1 and matches with Id in Data2, Data1$Group = Blue && Data1$Code == Data2$Id
2 - If the code is from Red Group in Data1 and matches with Id in Data2, Data1$Group = Red && Data1$Code == Data2$Id
0 - If the Id in Data2 does not match the Code in Data1 , regardless of whether it is Blue or Red group.
最终的数据集应该是这样的
Id Description Result
1333 Sea Weed 1
4444 Honey Roasted Peanut 1
8754 Green Tea 2
8756 Potato Chips 2
3145 Strawberry Grahams 2
8787 Arizona Ice Tea 0
需要帮助
【问题讨论】:
-
dat2$Result <- dat1$Group[match(dat2$Id, dat1$Code)]会给你颜色 - 然后你可以重新编码 -
@ :) 完美+1
-
由于您在帖子中包含标签“dplyr”,这里有一个“dplyr”答案:
dat2 <- dat2 %>% left_join(dat1,by=c('Id'='Code')) %>% select(Id,Description,Result=Group)(尽管基本 R 答案更容易遵循...)
标签: r if-statement dplyr