我有如下数据:
userID <- c(1,1,1,2,2,2,3,3,3)
product <- c("a","a","a","b","b","c","a","b","c")
df <- data.frame(userID, product)
对于每个“userID”,我想创建一个二进制指示变量,如果有多个唯一产品,则为 1,如果所有产品都相同,则为 0。
所以我的填充向量看起来像:
df$result <- c(0,0,0,1,1,1,1,1,1)
# userID product result
# 1 1 a 0
# 2 1 a 0
# 3 1 a 0
# 4 2 b 1
# 5 2 b 1
# 6 2 c 1
# 7 3 a 1
# 8 3 b 1
# 9 3 c 1
例如用户 1 只有一个不同的产品 ('a') -> 结果 = 0。用户 2 有多个独特的产品('b' 和 'c')-> 结果 = 1。
最佳答案
这里有一种方法可以实现这一点
library(data.table)
setDT(df)[, result := as.integer(uniqueN(product) > 1), by = userID]
# or
# setDT(df)[, result := as.integer(length(unique(product)) > 1), by = userID]
df
# userID product result
# 1: 1 a 0
# 2: 1 a 0
# 3: 1 a 0
# 4: 2 b 1
# 5: 2 b 1
# 6: 2 c 1
# 7: 3 a 1
# 8: 3 b 1
# 9: 3 c 1
或者
library(dplyr)
df %>%
group_by(userID) %>%
mutate(result = as.integer(n_distinct(product) > 1))
关于r - 根据组中唯一/不同值的数量创建二进制变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26379963/