使用dplyr合并两列 [英] Merge across two columns with dplyr

查看:340
本文介绍了使用dplyr合并两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking to merge across two columns which contain different data. That is where it is empty in one column it is not empty in another, essentially data collected from two different conditions in a study, in order to run analysis I need to combine this data and run t-tests. I was wondering how to combine numerical columns with 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"))


推荐答案

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

You can use dplyr::coalesce function which selects values from columns that first appear as non NA; say if you want to combine the first two columns:

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

这篇关于使用dplyr合并两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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