如何为列b的所有元素复制列a的每个元素?

时间:2016-01-12 18:57:56

标签: r

我有一个包含以下列的数据框:

月份:字符串

名称:字符串

数:数字。

我想取月份列并复制不同月份的所有名称,以便知道计数为0的位置,因为在数据集中,如果名称没有计数,则不记录日期。 / p>

可重复的例子:

test <- data.frame(month = c("Jan","Feb","Mar","Apr","Jan","Mar","Apr"), name = c("A","A","A","A","B","B","B"), count = c(1,4,5,7,3,2,5))

# Desired result

testresult <- data.frame(month = c("Jan","Feb","Mar","Apr","Jan","Feb","Mar","Apr"), name = c("A","A","A","A","B","B","B","B"), count = c(1,4,5,7,3,0,2,5))

2 个答案:

答案 0 :(得分:4)

我们可以将expand.gridmerge

一起使用
 merge(expand.grid(lapply(test[1:2], unique)), test, all.x=TRUE)

答案 1 :(得分:1)

# this may do what you want
# Create intermediate date frame with NA in missing counts
t1 <- reshape(test, idvar = "month", timevar = "name", direction = "wide")
# Create result data frame with original formats, and NA's included
testresult <- 
   reshape(t1, idvar = "month", timevar = "name", direction = "long")