R根据条件给出结果
R give a result based on a condition
非常感谢您的帮助。
我有一个带有 ID 的 table,列结果是 touchpoint_type。
当 ID 与前一个不同时,如果不是“I”,则给“C”。
那是我的代码:
mydata_cce2$touchpoint_type<-c(0)
mydata_cce2$touchpoint_type[1]="C"
j = 长度(mydata_cce2$id_transaction)
对于 (j in 2:(j-1)){
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
这就是我得到的错误:错误:“}”中的 inesperado '}'
Blockquote
您可以将 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了
非常感谢您的帮助。 我有一个带有 ID 的 table,列结果是 touchpoint_type。 当 ID 与前一个不同时,如果不是“I”,则给“C”。 那是我的代码: mydata_cce2$touchpoint_type<-c(0) mydata_cce2$touchpoint_type[1]="C" j = 长度(mydata_cce2$id_transaction) 对于 (j in 2:(j-1)){
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
这就是我得到的错误:错误:“}”中的 inesperado '}'
Blockquote
您可以将 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了