本文介绍了使用NA分解因数分解r中的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想折叠数据框,以使每行只有一个因子变量,并且所有值本身都折叠为每一行。下面是一个示例:
I want to collapse my dataframe so that there's only one factor variable per row and the values all collapse on themselves to one row each. Here's an example:
mat <- data.frame(type = c(rep("int",5), rep("num",5)), diag(sample.int(9,6), 10))
mat[mat == 0] <- NA
mat[5,11] <- 4
现在我要这样:
int,2,7,...,NA, NA,4
int, 2, 7, ...,NA, NA, 4
num,NA,NA,...,3,1
num, NA, NA, ..., 3, 1
推荐答案
按类型分组
,然后将 summarize_all
与 na.omit
:
mat %>% group_by(type) %>% summarise_all(funs(na.omit(.)[1]))
# A tibble: 2 x 11
# type X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# <fctr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 int 8 3 7 6 4 NA NA NA NA 4
#2 num NA NA NA NA NA 9 8 3 7 6
这篇关于使用NA分解因数分解r中的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!