簡體   English   中英

如何為列b的所有元素復制列a的每個元素?

[英]How to replicate every element of a column a for all elements of a column b?

我有一個包含以下列的數據框:

月:字符串

名稱:字符串

計數:數字。

我想使用month列並復制不同月份中的所有名稱,以便知道計數為0的原因,因為在數據集中,如果名稱沒有計數,則不會記錄日期。

可重現的示例:

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))

我們可以使用expand.gridmerge

 merge(expand.grid(lapply(test[1:2], unique)), test, all.x=TRUE)
# 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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM