R:使用tidyr清理结构缺失和冗余数据的数据表 [英] R: use tidyr to clean-up data table with structural missing and redundant data
问题描述
仍在尝试使用 tidyr
包.如果一个数据集有这样的冗余行:
Still trying to get my hands on tidyr
packages. If one has a data set with redundant rows like this:
require(dplyr)
require(tidyr)
data <-
data.frame(
v1 = c("ID1", NA, "ID2", NA),
v2 = c("x", NA, "xx", NA),
v3 = c(NA, "z", NA, "zz"),
v4 = c(22, 22, 6, 6),
v5 = c(5, 5, 9, 9)) %>%
tbl_df()
> data
Source: local data frame [4 x 5]
v1 v2 v3 v4 v5
1 ID1 x NA 22 5
2 NA NA z 22 5
3 ID2 xx NA 6 9
4 NA NA zz 6 9
由于 id 变量 v1
- v3
被拆分为具有许多 NA 的冗余行(因此也重复了两次测量),因此我们希望得到这样的结果下面:
Since the id variables v1
- v3
is split into redundant rows with many NAs (and therefore the two measurements are also repeated) one would like to get something like this below:
v1 v2 v3 v4 v5
1 ID1 x z 22 5
2 ID2 xx zz 6 9
使用 tidyr
获取此信息的一般方法是什么?我觉得它可以使用 gather()
来完成,但是怎么做?
What would be a general way of getting this using tidyr
? I feel it could be done using gather()
but how ?
推荐答案
一种方法是这样的.使用 zoo
包中的 na.locf()
,我替换了 v1
中的 NA.然后,我使用变量对数据进行分组.我再次使用 na.locf()
来处理 v3
.最后,我删除了 v2
中带有 NA 的行.
One way would be like this. Using na.locf()
from the zoo
package, I replaced NAs in v1
. Then, I grouped the data using the variable. I employed na.locf()
one more time to take care of v3
. Finally, I removed rows with NAs in v2
.
library(zoo)
library(dplyr)
mutate(data, v1 = na.locf(v1)) %>%
group_by(v1) %>%
mutate(v3 = na.locf(v3, fromLast = TRUE)) %>%
filter(complete.cases(v2)) %>%
ungroup
# v1 v2 v3 v4 v5
#1 ID1 x z 22 5
#2 ID2 xx zz 6 9
这篇关于R:使用tidyr清理结构缺失和冗余数据的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!