gpt4 book ai didi

在 R 中重新排列数据框

转载 作者:行者123 更新时间:2023-12-01 09:33:04 25 4
gpt4 key购买 nike

我有一个如下所示的数据框:

created_at  actor_attributes_email      type
3/11/12 7:28 jeremy@asynk.ch PushEvent
3/11/12 7:28 jeremy@asynk.ch PushEvent
3/11/12 7:28 jeremy@asynk.ch PushEvent
3/11/12 7:42 jeremy@asynk.ch IssueCommentEvent
3/11/12 11:06 d.bussink@gmail.com PushEvent
3/11/12 11:06 d.bussink@gmail.com PushEvent

现在我想按月/年重新排列它(仍然按时间排序,并且仍然保持行的完整性)。这应该为每个月创建 3 列,然后将与该月相关的所有数据(created_at、actor_attributes_email 和类型)放在这 3 列中,以便我得到以下标题(对于数据中存在的所有月份):

april_2011_created_at april_2011_actor_attributes_email april_2011_type may_2011_created_at may_2011_actor_attributes_email may_2011_type  

如何在 R 中完成此操作?

可在此处找到包含整个数据集的 CSV 文件: https://github.com/aronlindberg/VOSS-Sequencing-Toolkit/blob/master/rubinius_rubinius_sequencing/rubinius_6months.csv

这是 CSV 第一行的 dput():

structure(list(created_at = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 
3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 7L, 7L, 8L,
8L, 8L, 9L, 9L, 9L, 10L, 10L, 10L), .Label = c("2012-03-11 07:28:04",
"2012-03-11 07:28:19", "2012-03-11 07:42:16", "2012-03-11 11:06:13",
"2012-03-11 12:46:25", "2012-03-11 13:03:12", "2012-03-11 13:12:34",
"2012-03-11 13:14:52", "2012-03-11 13:30:14", "2012-03-11 13:30:48"
), class = "factor"), actor_attributes_email = structure(c(3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("",
"d.bussink@gmail.com", "jeremy@asynk.ch"), class = "factor"),
type = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L), .Label = c("IssueCommentEvent", "PushEvent"
), class = "factor")), .Names = c("created_at", "actor_attributes_email",
"type"), class = "data.frame", row.names = c(NA, -30L))

其他一些假设是:

  • 即使“PushEvent”(例如)重复 10 次,我也需要保留所有这些,因为我将使用 R 包 TraMineR 进行序列分析
  • 列可以不等长
  • 不同月份的列之间没有关系
  • 某月内的数据应以最早的时间优先排序
  • 2011 年 6 月和 2012 年 6 月的数据需要分列在不同的列中

最佳答案

Maiasaura 提供了一种使用 plyr 和 lubridate 完成工作的优雅方式。这是在基本 R 中实现它的稍微不那么优雅的方式。但与 Maiasaura 不同的是,这种方式最大限度地减少了 NA 行的数量。每个月的 NA 行数是该月的行数与任何月份的最大行数之间的差。

# split df by month
by.mon <- split(df, months(as.POSIXct(df$created_at)))

# rename the columns to include the month name
by.mon <- mapply(
function(x, mon.name) {
names(x) <- paste(mon.name, names(x), sep='_');
return(x)
}, x=by.mon, mon.name=names(by.mon), SIMPLIFY=FALSE)

# add an index column for merging on
by.mon.indexed <- lapply(by.mon, function(x) within(x, index <- 1:nrow(x)))

# merge all of the months together
results <- Reduce(function(x, y) merge(x, y, by='index', all=TRUE, sort=FALSE),
by.mon.indexed)

# remove the index column
final_result <- results[names(results) != 'index']

关于在 R 中重新排列数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12822784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com