我有一个数据集如下
日期< - rep(c(“Jan”,“Feb”),3)[1:5]组< - c(rep(字母[1:2],每个= 2),“c”)值< - 样本(1:10,5)
数据 </跨度> &lt; - data.frame(日期,组,值)
&GT; 数据 </跨度> 日期组值1 … 1月2日2月2日71月3日b 32月4日b 91月5日c 1
正如你所观察到的那样,对于c组它没有 数据 </跨度> 在日期= 2月。我如何制作一个数据集……
使用合并:
#get all combinations of 2 columns all.comb <- expand.grid(unique(data$Date),unique(data$Group)) colnames(all.comb) <- c("Date","Group") #merge with all.x=TRUE to keep nonmatched rows res <- merge(all.comb,data,all.x=TRUE) #convert NA to 0 res$value[is.na(res$value)] <- 0 #result res # Date Group value # 1 Feb a 3 # 2 Feb b 4 # 3 Feb c 0 # 4 Jan a 5 # 5 Jan b 7 # 6 Jan c 10
使用基础R,您可以使用 xtabs 包装成 as.data.frame :
xtabs
as.data.frame
as.data.frame(xtabs(formula = value ~ Date + Group, data = data)) # Date Group Freq #1 Feb a 8 #2 Jan a 6 #3 Feb b 4 #4 Jan b 1 #5 Feb c 0 #6 Jan c 10
运用 reshape2
reshape2
library(reshape2) melt(dcast(data, Date~Group, value.var="value",fill=0), id.var="Date") #values differ as there was no set.seed() # Date variable value #1 Feb a 1 #2 Jan a 10 #3 Feb b 7 #4 Jan b 4 #5 Feb c 0 #6 Jan c 5
或使用 dplyr
dplyr
library(dplyr) library(tidyr) data%>% spread(Group, value, fill=0) %>% gather(Group, value, a:c) # Date Group value #1 Feb a 1 #2 Jan a 10 #3 Feb b 7 #4 Jan b 4 #5 Feb c 0 #6 Jan c 5