【问题标题】:Merge across two columns with dplyr使用 dplyr 跨两列合并
【发布时间】:2023-04-07 14:57:01
【问题描述】:

我希望合并包含不同数据的两列。那就是一列是空的,另一列不是空的,本质上是从研究中的两个不同条件收集的数据,为了运行分析,我需要结合这些数据并运行 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"))

【问题讨论】:

  • 如果您向reproducible example 提供示例输入数据和所需输出,会更容易为您提供帮助。
  • 没有数据时是NA还是0?你可以使用max函数
  • check$cat &lt;- apply(check[,1:2], 1, max) 这应该适用于两种情况。
  • @Masoud 我试过了,但它没有用,虽然很奇怪,似乎它应该可以工作,而且值也是 NA
  • 你能检查你的数据的类别,如果它是数字的吗?提供此信息,您的问题将立即得到解答:dput(head(check))

标签: r dplyr


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 2021-04-19
    • 2021-03-20
    • 2021-08-10
    • 2015-05-06
    • 2019-03-28
    • 1970-01-01
    相关资源
    最近更新 更多