r - 根据组中唯一/不同值的数量创建二进制变量

标签 r dataframe data-manipulation split-apply-combine

我有如下数据:

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/

相关文章:

Netcdf 气候数据的栅格图在 R 中旋转

r - 在 R 中列出没有子文件夹的文件夹中的所有文件

r - 将句子的第一个单词大写(regex、gsub、gregexpr)

python - Pandas Dataframe -(列重组)

python - pandas 中的 where、mask 和 df[S>0] 有什么区别?

r - 在 R 中的字符串中不存在的数据框中创建列

r - "These samplers cannot be used in parallelized code"

python - 如何从 CSV 文件创建 Target(y) 和 X 变量

r - 如何重新排列/操作数据?

r - 根据变量是否在列表中对数据进行子集化