使用条件聚合上一列的数据

时间:2018-01-24 08:12:16

标签: r aggregation

我想汇总约翰和约书亚的消费点,最新的事件是当前的更新点。

输入数据:

v1 = c("event1", "event2", "event3")
v2 = c("garlicX", "onionY", "cucumberX")
v3 = c("John", "John", "John")
v4 = c("Joshua", "Joshua", "Joshua")

#John's table points
x1 = c("garlicJohn", "OnionJohn", "CucumberJohn")
x2 = c(1, 2, 3)

#Joshua's table points
x3 = c("garlicJoshua", "OnionJoshua", "CucumberJoshua")
x4 = c(1, 2, 3)


df0 = data.frame(x1,x2,x3,x4)
df1 = data.frame(v1,v2,v3,v4)

期望的输出:

#v5 John's aggregate score
#v6 Joshua's aggregate score

    v1        v2    v3     v4   v5 v6
event1   garlicJohn John Joshua  1  0
event2  onionJoshua John Joshua  1  2
event3 cucumberJohn John Joshua  4  2

1 个答案:

答案 0 :(得分:2)

花了一些时间来计算v5和v6列。此外,我注意到x1和x3的洋葱和黄瓜以Capital开头,而我改为小写字母的事实不一致。这可能不是最好的解决方案,但是你去了:

v1 = c("event1", "event2", "event3")
v2 = c("garlicX", "onionY", "cucumberX")
v3 = c("John", "John", "John")
v4 = c("Joshua", "Joshua", "Joshua")

df1 = data.frame(v1, v2, v3, v4, stringsAsFactors = FALSE)

x1 = c("garlicJohn", "onionJohn", "cucumberJohn")
x2 = c(1, 2, 3)
x3 = c("garlicJoshua", "onionJoshua", "cucumberJoshua")
x4 = c(1, 2, 3)

df0 = data.frame(x1, x2, x3, x4, stringsAsFactors = FALSE)

forJohn <- 'X'
forJoshua <- 'Y'

for(i in 1:3) {
  if(grepl(forJohn, df1$v2[i])) {
    str1 <- strsplit(df1$v2[i], forJohn)
    str2 <- 'John'
    df1$v2[i] <- paste0(str1, str2)
  } else if(grepl(forJoshua, df1$v2[i])) {
    str1 <- strsplit(df1$v2[i], forJoshua)
    str2 <- 'Joshua'
    df1$v2[i] <- paste0(str1, str2)
  }
}

for(i in 1:3) {
  if(grepl(df1$v2[i], df0$x1[i])) {
    if(i == 1) {
      df1$v5[i] <- i
    } else{
      df1$v5[i] <- i + df1$v5[i-1]
    }
  } else {
    if(i == 1) {
      df1$v5[i] <- 0
    } else {
      df1$v5[i] <- df1$v5[i-1]
    }
  }
}

for(i in 1:3) {
  if(grepl(df1$v2[i], df0$x3[i])) {
    if(i == 1) {
      df1$v6[i] <- i
    } else{
      df1$v6[i] <- i + df1$v6[i-1]
    }
  } else {
    if(i == 1) {
      df1$v6[i] <- 0
    } else {
      df1$v6[i] <- df1$v6[i-1]
    }
  }
}

结果:

      v1           v2   v3     v4 v5 v6
1 event1   garlicJohn John Joshua  1  0
2 event2  onionJoshua John Joshua  1  2
3 event3 cucumberJohn John Joshua  4  2

编辑:如果有人想知道如何计算v5和v6。这是解释。

大蒜约翰和大蒜约书亚被映射到1,同样,洋葱约翰,洋葱乔沙,黄瓜约翰和黄瓜约书亚分别映射到2,2,3和3。

现在,从df1的v2列开始,我们需要检查df0 dataframe的值是什么。 garlicJohn对应1. v5需要基于John汇总值,而v6则基于Joshua汇总。因此,对于v5,garlicJohn将为1,对于v6将为0。我们现在有了onionJosha,这意味着v5第二行保持这样,而v6第二行变为2.对于最后一行,在v5中,我们将当前映射值添加到前一个索引(3 + 1)的值,而v6仍然存在相同。