如何使用dplyr合并具有NA的列?

a2mppw5e  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(145)

我希望使用dplyr组合多列中有NA的行。我还没有找到解决这个问题的方法。我对R还是个新手,所以提前道歉。
我想更改此示例数据框:

# Groups:   RID, FlankerCongruence, NoiseLevel 
     RID FlankerCongruence TrialStim.ACC NoiseLevel TrialStim.RT  
   <int> <chr>                     <int>      <int>        <int> 
 1   101 Congruent                     1          0           NA    
 2   101 Congruent                     1          0           NA     
 3   101 Congruent                     1          0           NA    
 4   101 Congruent                    NA          0          678   
 5   101 Congruent                    NA          0          909   
 6   101 Congruent                    NA          0          928

变成这样的东西

# Groups:   RID, FlankerCongruence, NoiseLevel 
    RID FlankerCongruence TrialStim.ACC NoiseLevel TrialStim.RT  
   <int> <chr>                     <int>      <int>        <int> 
 1   101 Congruent                     1          0          678     
 2   101 Congruent                     1          0          909     
 3   101 Congruent                     1          0          928

我第一次尝试使用这个:

coalesce_by_column <- function(noMeancombinedNoiseTable.data) {
  return(dplyr::coalesce(!!! as.list(noMeancombinedNoiseTable.data)))
}

noMeancombinedNoiseTable.data <- noMeancombinedNoiseTable.data %>%
  group_by(RID, FlankerCongruence, NoiseLevel) %>% 
  arrange(RID, FlankerCongruence, NoiseLevel) %>%
  summarise_all(coalesce_by_column)

但它总结了如下列:

RID FlankerCongruence NoiseLevel TrialStim.ACC TrialStim.RT 
   <int> <chr>                  <int>         <int>        <int> 
 1   101 Congruent                  0             1          678

有什么建议吗?

c3frrgcw

c3frrgcw1#

我们可以按列进行分组,重新排列其他列中的NA,并保留至少有一个非NA值的行

library(dplyr)
noMeancombinedNoiseTable.data %>%
  group_by(RID, FlankerCongruence, NoiseLevel) %>%
  mutate(across(everything(), ~ .x[order(!is.na(.x))])) %>%
  filter(if_any(everything(), ~ !is.na(.x))) %>%
  ungroup
  • 输出
# A tibble: 3 × 5
    RID FlankerCongruence TrialStim.ACC NoiseLevel TrialStim.RT
  <int> <chr>                     <int>      <int>        <int>
1   101 Congruent                     1          0          678
2   101 Congruent                     1          0          909
3   101 Congruent                     1          0          928

数据

noMeancombinedNoiseTable.data <- structure(list(RID = c(101L, 101L, 
101L, 101L, 101L, 101L), FlankerCongruence = c("Congruent", 
"Congruent", "Congruent", "Congruent", "Congruent", "Congruent"
), TrialStim.ACC = c(1L, 1L, 1L, NA, NA, NA), NoiseLevel = c(0L, 
0L, 0L, 0L, 0L, 0L), TrialStim.RT = c(NA, NA, NA, 678L, 909L, 
928L)), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6"))

相关问题