如何从R中每个日期的一列值中为每个特定值创建一个数据框?
我拥有的数据帧格式如下:如何从R中每个日期的一列值中为每个特定值创建一个数据框?,r,dataframe,R,Dataframe,我拥有的数据帧格式如下: dates <- c("02/27/92", "02/27/92", "02/28/92", "02/28/92", "02/28/92", "02/29/92", "02/29/92") df_Before <- data.frame(Date = as.Date(dates, "%m/%d/%y"), ID = c(1,1,2,2,2,3,3), Var1 = factor(c('d','c','d'
dates <- c("02/27/92", "02/27/92", "02/28/92", "02/28/92", "02/28/92", "02/29/92", "02/29/92")
df_Before <- data.frame(Date = as.Date(dates, "%m/%d/%y"),
ID = c(1,1,2,2,2,3,3),
Var1 = factor(c('d','c','d','b','c','a','b')))
> df_Before
Date ID Var1
1 1992-02-27 1 d
2 1992-02-27 1 c
3 1992-02-28 2 d
4 1992-02-28 2 b
5 1992-02-28 2 c
6 1992-02-29 3 a
7 1992-02-29 3 b
提前谢谢 Reforme2库具有此类型应用程序的dcast函数
library(reshape2)
dcast(df_Before, Date+ID~Var1, length)
# Date ID a b c d
#1 1992-02-27 1 0 0 1 1
#2 1992-02-28 2 0 1 1 1
#3 1992-02-29 3 1 1 0 0
您可以使用
cast
功能来执行此操作,这是一个更基本的R:
library(reshape)
df_Before$values <- 1 # Need to add this one column in order to aggregate.
df_After <- cast(df_Before, formula = Date + ID ~ Var1, sum, value = "values")
没关系,其他人在上面的
dcast
中发布了一个更好的
library(reshape)
df_Before$values <- 1 # Need to add this one column in order to aggregate.
df_After <- cast(df_Before, formula = Date + ID ~ Var1, sum, value = "values")
> df_After
Date ID a b c d
1 1992-02-27 1 0 0 1 1
2 1992-02-28 2 0 1 1 1
3 1992-02-29 3 1 1 0 0