R-数据帧中的有效分隔组 [英] R - Efficiently Separate Groups in Data Frame

查看:78
本文介绍了R-数据帧中的有效分隔组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户统计数据,格式如下:

I have a data set of user stats of the following form:

df
   user       date   group
1    X 2017-06-21   S;Y;J
2    Y 2017-06-09 Y;F;P;C
3    R 2017-12-29     K;A
4    Q 2017-08-31     W;I
5    B 2018-01-30   P;M;E

可以通过以下方式生成

set.seed(10)
n = 5
dates <- seq.Date(as.Date("2017-04-01"), as.Date("2018-05-01"), by=1)
df <- data.frame(user = sample(LETTERS, n, replace=TRUE),
             date = sample(dates, n, replace=TRUE))

df$group <- "A"
for(i in 1:n){
df$group[i] <- paste(sample(LETTERS, sample(1:5, 1, replace=FALSE), 
                       replace=FALSE), collapse=";")
}

我想拆分并扩展group列,使其与日期和用户指定的匹配.例如,用户X2017-06-21上的三个组进行了交互,我希望将其作为三个单独的条目而不是一个条目.我有适用于此的代码,但是我正在寻找一种更快,更R友好的方式来复制它.我当前的解决方案是:

I want to split and expand the group column so that it matches the date and user given. For example, User X has interacted with three groups on 2017-06-21, which I'd like to have as three separate entries instead of one. I have code that works for this, but I'm looking for a faster, more R friendly way of replicating this. My current solution is:

# Get the number of groups for each entry
n_groups <- 1 + gsub("[^;]", "", df$group) %>% nchar()
# Get the index for the entries with multiple groups
index <- which(n_groups > 1)
# Get a new vector of dates and users
dates <- integer(sum(n_groups))
class(dates) <- "Date"
users <- vector(mode='character', 
                length = sum(n_groups))

k <- 1
for(i in 1:length(n_groups)){
  for(j in 1:n_groups[i]){
    dates[k] <- df$date[i]
    users[k] <- as.character(df$user[i])
    k <- k + 1
  }
}

df2 <- data.frame(date = dates, user = users,
                  group = unlist(strsplit(df$group, split = ";")))
df2
         date user group
1  2017-06-21    X     S
2  2017-06-21    X     Y
3  2017-06-21    X     J
4  2017-06-09    Y     Y
5  2017-06-09    Y     F
6  2017-06-09    Y     P
7  2017-06-09    Y     C
8  2017-12-29    R     K
9  2017-12-29    R     A
10 2017-08-31    Q     W
11 2017-08-31    Q     I
12 2018-01-30    B     P
13 2018-01-30    B     M
14 2018-01-30    B     E

推荐答案

library(dplyr)
library(tidyr)

df2 <- df %>% 
  mutate(group = strsplit(group, split = ";")) %>%
  unnest(group) %>%
  select(date, user, group)

这篇关于R-数据帧中的有效分隔组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆