分组(折叠?)行,而无需汇总即可填写NA [英] Group (collapse?) rows without summarising to fill in NAs

查看:40
本文介绍了分组(折叠?)行,而无需汇总即可填写NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得dplyr应该很简单(我认为),但是我似乎找不到解决方法.

I have an issue that should be straightforward with dplyr (I think) but I can't seem to find a resolution.

我的数据框包含数字和因子.每个观察值由两行表示,这两行在两列(Agg_Entropy和Av_Amplitude)之一中具有值或NA.我想将每个观察值的行合并为一行(不进行汇总),以便将NA替换为相关值.

My dataframe comprises numbers and factors. Each observation is represented by two rows which have either a value or NA in one of two columns (Agg_Entropy and Av_Amplitude). I want to combine each observation's rows into a single row (without summarising), so that the NAs are replaced with the relevant values.

数据框的简单摘录:

 Selection Low   High    Agg_Entropy Av_Amplitude Filename                  
  <fct>     <fct> <fct>         <dbl>        <dbl> <fct>                     
1 1         368.2 13747.8       NA           -17.5 20180110_182800_Sunset.wav
2 1         368.2 13747.8        5.62         NA   20180110_182800_Sunset.wav
3 2         142   13926.3       NA           -17.4 20180110_182800_Sunset.wav
4 2         142   13926.3        5.96         NA   20180110_182800_Sunset.wav

我想要什么:

 Selection   Low    High Agg_Entropy Av_Amplitude                   Filename
1         1 368.2 13747.8       5.623        -17.5 20180110_182800_Sunset.wav
2         2 142.0 13926.3       5.958        -17.4 20180110_182800_Sunset.wav

非常感谢您的帮助.谢谢!

Any help is very much appreciated. Thank you!

推荐答案

group_by 之后,列为'Selection','Filename','Low'和'High', summarise 其他列,方法是使用 na.omit 删除 NA 元素.在这里,我们假设组的每一列只有一个非NA元素

After group_by with columns 'Selection', 'Filename', 'Low', and 'High', summarise the other columns by removing the NA elements with na.omit. Here, we assume that there are only one non-NA element per each column for the groups

library(tidyverse)
df1 %>%
   group_by(Selection, Filename, Low, High) %>%
   summarise_all(na.omit)

这篇关于分组(折叠?)行,而无需汇总即可填写NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆