【发布时间】:2019-02-15 22:28:24
【问题描述】:
我有一个示例表,其中包含 一些 但不是所有需要替换的 NA 值。
> dat
id message index
1 1 <NA> 1
2 1 foo 2
3 1 foo 3
4 1 <NA> 4
5 1 foo 5
6 1 <NA> 6
7 2 <NA> 1
8 2 baz 2
9 2 <NA> 3
10 2 baz 4
11 2 baz 5
12 2 baz 6
13 3 bar 1
14 3 <NA> 2
15 3 <NA> 3
16 3 bar 4
17 3 <NA> 5
18 3 bar 6
19 3 <NA> 7
20 3 qux 8
我的目标是使用第一次出现的消息(最少的index 值)和最后一次出现的消息替换由相同“消息”包围的NA 值消息(使用最大 index 值)按 id
有时,NA 序列的长度仅为 1,有时它们可能很长。无论如何,应该填写所有“夹在”NA 前后相同“消息”值之间的 NA。
上述不完整表格的输出将是:
> output
id message index
1 1 <NA> 1
2 1 foo 2
3 1 foo 3
4 1 foo 4
5 1 foo 5
6 1 <NA> 6
7 2 <NA> 1
8 2 baz 2
9 2 baz 3
10 2 baz 4
11 2 baz 5
12 2 baz 6
13 3 bar 1
14 3 bar 2
15 3 bar 3
16 3 bar 4
17 3 bar 5
18 3 bar 6
19 3 <NA> 7
20 3 qux 8
任何使用data.table 或dplyr 的指导都会有所帮助,因为我什至不知道从哪里开始。
据我所知,唯一消息是子集,但这种方法没有考虑到id:
#get distinct messages
messages = unique(dat$message)
#remove NA
messages = messages[!is.na(messages)]
#subset dat for each message
for (i in 1:length(messages)) {print(dat[dat$message == messages[i],]) }
数据:
dput(dat)
structure(list(id = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3,
3, 3, 3, 3, 3, 3, 3), message = c(NA, "foo", "foo", NA, "foo",
NA, NA, "baz", NA, "baz", "baz", "baz", "bar", NA, NA, "bar",
NA, "bar", NA, "qux"), index = c(1, 2, 3, 4, 5, 6, 1, 2, 3, 4,
5, 6, 1, 2, 3, 4, 5, 6, 7, 8)), row.names = c(NA, -20L), class = "data.frame")
【问题讨论】:
-
你能澄清一下你的意思吗?即,如果在此数据中,第 6 行有“foo”,第 8 行也有,那么第 7 行仍然不会被填充,而是会丢失?我认为您的数据示例中目前没有说明这一点
-
没错,因为第 6 行的
id是 1 而第 8 行的id是 2,所以在这种情况下 7 会乱七八糟。如果第 7 行是“foo”,由于 id 不同,第 6 行仍将保持 NA
标签: r dplyr data.table