在R中按索引组合行 [英] Combining rows by index in R
问题描述
我知道已经回答了一个类似的问题,但它对我在下面提供的数据集上不起作用.上面的数据帧是我使用扩展函数的结果.我仍然不确定如何整合它.
I am aware there is a similar question that has been answered, but it does not work for me on the dataset I have provided below. The above dataframe is the result of me using the spread function. I am still not sure how to consolidate it.
我意识到我之前在数据上使用的 group_by 函数阻止了扩展函数以我最初希望的方式工作.使用 ungroup 后,我可以直接从原始数据集(下图未显示)转到下图中的第二个数据框.
I realized that the group_by function, which I had previously used on the data, is what was preventing the spread function from working in the way I wanted it to work originally. After using ungroup, I was able to go straight from the original dataset (not pictured below) to the 2nd dataframe pictured below.
我有一个如下所示的数据框.我正在尝试使每个 ID 号只有 1 行.
I have a dataframe that looks like the following. I am trying to make it so that there is only 1 row for each id number.
id init_cont family 1 2 3
1 I C 1 NA NA
1 I C NA 4 NA
1 I C NA NA 3
2 I D 2 NA NA
2 I D NA 1 NA
2 I D NA NA 4
3 K C 3 NA NA
3 K C NA 4 NA
3 K C NA NA 1
我希望生成的数据框看起来像这样.
I would like the resulting dataframe to look like this.
id init_cont family 1 2 3
1 I C 1 4 3
2 I D 2 1 4
3 K C 3 4 1
推荐答案
我们可以group_by
'd', 'init_cont', 'family' 然后做一个summarise_all
删除列 1:3
We cangroup_by
the 'd', 'init_cont', 'family' and then do a summarise_all
to remove all the NA
elements in the columns 1:3
library(dplyr)
df1 %>%
group_by_at(names(.)[1:3]) %>%
summarise_all(na.omit)
#Or
#summarise_all(funs(.[!is.na(.)]))
# A tibble: 3 x 6
# Groups: d, init_cont [?]
# d init_cont family `1` `2` `3`
# <int> <chr> <chr> <int> <int> <int>
#1 1 I C 1 4 3
#2 2 I D 2 1 4
#3 3 K C 3 4 1
这篇关于在R中按索引组合行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!