使用dplyr合并两列

时间:2017-07-24 20:22:56

标签: r dplyr

我希望合并两个包含不同数据的列。这就是在一列中它是空的,在另一列中它是空的,本质上是从研究中的两个不同条件收集的数据,为了运行分析,我需要将这些数据和运行t检验结合起来。我想知道如何将数字列与dplyr组合 -

check <- check %>% 
  mutate(cat = rowSums(.[1:2]))


> dput(head(check))
structure(list(t7_1_ExpA_Intro1 = c(NA_integer_, NA_integer_, 
NA_integer_, NA_integer_, NA_integer_, NA_integer_), t7_1_ExpB_Intro1 = c(NA, 
NA, NA, 3L, NA, NA), t7_1_ExpA_DV = c(NA_integer_, NA_integer_, 
NA_integer_, NA_integer_, NA_integer_, NA_integer_), t7_1_ExpB_DV = c(NA, 
NA, NA, 3L, NA, NA), cat = c(NA_integer_, NA_integer_, NA_integer_, 
NA_integer_, NA_integer_, NA_integer_)), .Names = c("t7_1_ExpA_Intro1", 
"t7_1_ExpB_Intro1", "t7_1_ExpA_DV", "t7_1_ExpB_DV", "cat"), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

1 个答案:

答案 0 :(得分:2)

您可以使用dplyr::coalesce函数从首先显示为非NA的列中选择值;如果你想要合并前两列:

check %>% mutate(cat = coalesce(t7_1_ExpA_Intro1, t7_1_ExpB_Intro1))
# or check %>% mutate(cat = do.call(coalesce, .[1:n])) if you have more columns to coalesce

# A tibble: 6 x 5
#  t7_1_ExpA_Intro1 t7_1_ExpB_Intro1 t7_1_ExpA_DV t7_1_ExpB_DV   cat
#             <int>            <int>        <int>        <int> <int>
#1               NA               NA           NA           NA    NA
#2               NA               NA           NA           NA    NA
#3               NA               NA           NA           NA    NA
#4               NA                3           NA            3     3
#5               NA               NA           NA           NA    NA
#6               NA               NA           NA           NA    NA