【问题标题】:R give a result based on a conditionR根据条件给出结果
【发布时间】:2016-05-19 18:38:30
【问题描述】:

非常感谢您的帮助。 我有一个带有 ID 的表,列结果是 touchpoint_type。 当 ID 与前一个不同时,我给“C”,如果不是“I”。 这是我的代码: mydata_cce2$touchpoint_type

  if (mydata_cce2$id_transaction[j] != mydata_cce2$id_transaction[j-1]) 

    { mydata_cce2$touchpoint_type[j] ="C"

  } 

  else { 

    mydata_cce2$touchpoint_type[j] = "I"

  }

}
This is the results that I should get:
id_transaction  touchpoint_type 
    id_transaction  touchpoint_type
1   68013539    C
2   68013539    I
3   68013539    I
4   68013702    C
5   68013738    C
6   68013738    I

这是我得到的错误:Error:inesperado '}' in "}"

Blockquote

【问题讨论】:

标签: r if-statement conditional


【解决方案1】:

您可以将ifelse()shift() 结合使用。

#Data
df <- read.table(header=TRUE,text="id_transaction
   68013539    
   68013539    
   68013539    
   68013702    
   68013738    
   68013738")

library(data.table)
df$touchpoint_type <- ifelse(shift(df$id_transaction,n=1L,type="lag") == df$id_transaction, "I","C")

df
  id_transaction touchpoint_type
1       68013539            <NA>
2       68013539               I
3       68013539               I
4       68013702               C
5       68013738               C
6       68013738               I

请注意第一个条目不是“C”的原因是因为它是我的示例数据框中的第一个条目。如果上面有东西,那就不是NA了。

【讨论】:

  • 抱歉 MikeyMike,R 说它找不到函数“shift”。你为什么会这样?非常感谢
  • 它在data.table 包中。我已经更新了我的代码。很抱歉没有包括在内。
  • np!如果您认为它有帮助,请随时点击我的回复旁边的勾选。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2020-08-28
相关资源
最近更新 更多