在其他相同的行中组合单个唯一变量

Combine single unique variable in otherwise identical rows

我正在从一个 API 跟踪花费在项目上的时间中提取数据,变量包括时间、客户、项目和 - 可能 - 描述项目的多个标签。然而,当我提取数据时,具有多个标签的条目被复制到其他相同的行中,每行有一个唯一的标签,如下所示:

 duration client project    tag
       60      A       X  first
       45      B       Y second
       45      B       Y  third
       30      C       Z fourth

如何在组合标签时删除重复的行?我在想:

A)
  duration client project    tags
1       60      A       X   first
2       45      B       Y  second, third
3       30      C       Z  fourth

或者这个:

B)
  duration client project    tag1   tag2
1       60      A       X   first     NA
2       45      B       Y  second  third
3       30      C       Z  fourth     NA

我也很感激关于哪种建议安排(A 或 B)最适合快速总结花费在项目上的时间量的建议,例如,标签 "first" 和 "third"(例如 105 分钟)?

这是示例数据框:

df <- data.frame(
  duration = c(60, 45, 45, 30),
  client = c("A", "B", "B", "C"),
  project = c("X", "Y", "Y", "Z"),
  tag = c("first", "second", "third", "fourth")
  )

我很感激任何建议(我觉得 dplyr/tidyr 应该不会太难,但还没有完全正确)。谢谢!

我觉得你的解决方案 A 不错。我会这样做:-

library(data.table)

setDT(df)
df <- df[, tags := paste0(tag, collapse = ", "), by = project]
df[, tag := NULL]
df <- unique(df)

它会给你一个你想要的结果:

duration client project   tags
1:  60      A       X     first
2:  45      B       Y     second, third
3:  30      C       Z     fourth

我会用 plyr 作为 A)

library(plyr)
df2 <- ddply(df, .(client), function(df){
  tags<- paste(df$tag, collapse=",")
  df$tag <- tags
  df[1,]
})

我们可以使用 dplyr 作为输出 A。group_by_at(vars(-tag)) 是一种指定分组变量应该是除 tag 之外的所有列的方法,因为您希望所有其他列都是准确的在行中复制。

library(dplyr)

df2 <- df %>%
  group_by_at(vars(-tag)) %>%
  summarise(tags = toString(tag)) %>%
  ungroup()
df2
# # A tibble: 3 x 4
#   duration client project          tags
#      <dbl> <fctr>  <fctr>         <chr>
# 1       30      C       Z        fourth
# 2       45      B       Y second, third
# 3       60      A       X         first

然后我们可以使用 splitstackshape 作为输出 B

library(splitstackshape)
df3 <- df2 %>% cSplit(splitCols = "tags")
df3
#    duration client project tags_1 tags_2
# 1:       30      C       Z fourth     NA
# 2:       45      B       Y second  third
# 3:       60      A       X  first     NA