关闭但不重复:在 tidyr/dplyr 中添加零计数行的正确习惯用法- 我试图根据 df 中的现有值进行填充,但也根据没有id. 相似,但本质不同。
对于每个id,我试图确保每个都有 3 个计费月。
理想情况下,对于每个id我都需要所有三个required months都出现在df_complete. 如果它不在数据中,我希望为值添加一行“未找到”。
此外,我想检查all_ids并添加在其中all_ids但没有行的IDdf
months <- as.data.frame(as.Date(c("2016/7/1","2016/9/1","2016/7/1", "2016/8/1","2016/9/1", "2016/8/1","2016/9/1")))
id <- as.data.frame(c("a","a","b","b","b","c","c"))
value <- as.data.frame(c(1,2,3,4,5,6,7))
df <- cbind(id,months,value)
colnames(df) <- c("id","billing months","value")
required_months <- as.data.frame(as.Date(c("2016/7/1", "2016/8/1","2016/9/1")))
colnames(required_months)<- "required months"
all_ids <- as.data.frame(c("a","b", "c", "d"))
Run Code Online (Sandbox Code Playgroud)
df 最终看起来像:
id billing months value
a 7/1/2016 1
a 9/1/2016 2
b 7/1/2016 3
b 8/1/2016 4
b …Run Code Online (Sandbox Code Playgroud) 任何人都可以弄清楚为什么这不起作用?
test<-c(1,2,3,4)
adding<-function(file){
file2<- file + 1
return(file2)
}
adding(file = 1)
Run Code Online (Sandbox Code Playgroud)
收益率:
> adding(file = 1)
[1] 2
Run Code Online (Sandbox Code Playgroud)
但是当我尝试:
for(number in test){
adding(number)
print(number)
}
Run Code Online (Sandbox Code Playgroud)
我明白了:
> for(number in test){
+ adding(number)
+ print(number)
+ }
[1] 1
[1] 2
[1] 3
[1] 4
Run Code Online (Sandbox Code Playgroud)
当我期待:
[1] 2
[1] 1
[1] 3
[1] 2
[1] 4
[1] 3
[1] 5
[1] 4
Run Code Online (Sandbox Code Playgroud)
我正在将这个基础用于for loop我正在研究的另一个基础,并想知道它为什么不起作用.