Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

dplyr - Collapse dataframe in r by factor with NAs

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

Now I want this to be:

type, X1, ..., X8, X9, X10

int, 2, 7, ...,NA, NA, 4

num, NA, NA, ..., 3, 1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Group by type, then use summarize_all with 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...