我有一个数据框,其序列在'col1'中,值在'col2'中:
col1 col2
2 0.02
5 0.12
9 0.91
13 1.13
Run Code Online (Sandbox Code Playgroud)
我想用1到13的常规序列扩展'col1'中的不规则序列.对于原始数据中缺少的'col1'中的值,我希望'col2' 0在最终输出中得到值:
col1 col2
1 0
2 0.02
3 0
4 0
5 0.12
6 0
7 0
8 0
9 0.91
10 0
11 0
12 0
13 1.13
Run Code Online (Sandbox Code Playgroud)
我怎么能在R中这样做?
只是为了完整性,使用自我二进制连接data.table(你将得到NAs而不是零,但如果需要可以很容易地改变)
library(data.table)
setDT(df)[.(seq(max(col1))), on = .(col1)]
# col1 col2
# 1: 1 NA
# 2: 2 0.02
# 3: 3 NA
# 4: 4 NA
# 5: 5 0.12
# 6: 6 NA
# 7: 7 NA
# 8: 8 NA
# 9: 9 0.91
# 10: 10 NA
# 11: 11 NA
# 12: 12 NA
# 13: 13 1.13
Run Code Online (Sandbox Code Playgroud)
library(tidyr)
complete(d, col1 = 1:13, fill = list(col2 = 0))
Run Code Online (Sandbox Code Playgroud)
要么
complete(d, col1 = seq(max(col1))), fill = list(col2 = 0))
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)# A tibble: 13 × 2 col1 col2 <int> <dbl> 1 1 0.00 2 2 0.02 3 3 0.00 4 4 0.00 5 5 0.12 6 6 0.00 7 7 0.00 8 8 0.00 9 9 0.91 10 10 0.00 11 11 0.00 12 12 0.00 13 13 1.13
要么
library(dplyr)
left_join(data.frame(col1 = seq(max(d$col1)))), d)
Run Code Online (Sandbox Code Playgroud)
但这将留下NAs而不是零.