Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...