我想做的是折叠我的数据框,以便每个唯一日期都有与之关联的相应变量。这是我现在的数据样本(仅供引用:我使用的完整数据集大约有 300 个观测值。具有不同的日期):
date <- c("10/30/17", "10/30/17", "10/30/17", "10/30/17")
eventcode <- c("14", "14", "14", "14")
eoi145 <- c(1, 0, 0, 0)
eoi140 <- c(0, 1, 0, 0)
eoi141 <- c(0, 0, 0, 1)
eoi143 <- c(0, 0, 1, 0)
df <- data.frame(date, eventcode, eoi145, eoi140, eoi141, eoi143)
View(df)
我想进入这种格式:
date <- c("10/30/17")
eventcode <- c("14")
eoi145 <- c(1)
eoi140 <- c(1)
eoi141 <- c(1)
eoi143 <- c(1)
df <- data.frame(date, eventcode, eoi145, eoi140, eoi141, eoi143)
我尝试过使用 cast、melt 和 reshape。任何人都可以给我一个关于任何包或技术来完成这个的提示。
谢谢!
最佳答案
dplyr 包中的一种方法:
library(dplyr)
reduced_df <- df %>%
group_by(date, eventcode) %>%
summarise_all(funs(as.integer(sum(.)))) %>%
ungroup()
输出:
# A tibble: 1 x 6
# date eventcode eoi145 eoi140 eoi141 eoi143
# <fct> <fct> <int> <int> <int> <int>
# 10/30/17 14 1 1 1 1
关于r - 将数据框折叠到唯一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48409102/