在R中满足多个if条件之后将值从一个数据帧粘贴到另一个数据帧

时间:2019-07-14 15:49:11

标签: r dataframe if-statement

我试图将一个数据框中的唯一值粘贴到单独数据框中的新创建的列中。该功能需要满足多个条件。在这种情况下,两个数据框中的“日期”和“产品”值必须相同。

我曾经尝试过使用if和while函数,但是我似乎无法破解问题。

sales1 <- data.frame("Day" = c(01,02,03,04), "Product" = c("B","A","D","C"), "salesVol" = c(12,31,3,90))
sales2 <- data.frame("Day" = c(01,01,01,01,02,02,02,02,03,03,03,03,04,04,04,04), "Product" = c("A","B","C","D","A","B","C","D","A","B","C","D","A","B","C","D"), "Price" = c(9,3,4,5,7,10,5,8,4,5,11,3,12,4,7,6))
for (i in 1:nrow(sales1)){
  if (sales1$Product == sales2$Product
      && sales1$Day == sales2$Day)
  {
    sales1$dailyPrice[i] <- sales2$Price[i]
  }
}

请注意,sales2中只能有一种日期/产品的唯一组合。

也尝试过:

while (sales1$Product == sales2$Product
       && sales1$Day == sales2$Day){
    sales1$dailyPrice <- sales2$Price
}

结果sales1数据框应为:

Day Product salesVol dailyPrice
1    B        12       3
2    A        31       7
3    D        3        3
4    C        90       7

即当日期为2,产品为“ A”时,按销售额计算,“每日价格”为7。

但是,最好的情况下,我得到的值不正确,而最糟糕的是(上面的代码)没有任何粘贴。也没有错误消息。谢谢。

1 个答案:

答案 0 :(得分:3)

这是您想要的吗?

merge(sales1,sales2,by=c("Day","Product"))

这就是一切:

  sales1 <- data.frame("Day" = c(01,02,03,04),
 "Product" = c("B","A","D","C"), "salesVol" = c(12,31,3,90))
  sales2 <- data.frame("Day" = c(01,01,01,01,02,02,02,02,03,03,03,03,04,04,04,04),
  "Product" = c("A","B","C","D","A","B","C","D","A","B","C","D","A","B","C","D")
    , "Price" = c(9,3,4,5,7,10,5,8,4,5,11,3,12,4,7,6))
sales1
sales2
merge(sales1,sales2,by=c("Day","Product"))