• 主页
  • 课程

    关于课程

    • 课程归档
    • 成为一名讲师
    • 讲师信息
    同等学历教学

    同等学历教学

    免费
    阅读更多
  • 特色
    • 展示
    • 关于我们
    • 问答
  • 事件
  • 个性化
  • 博客
  • 联系
  • 站点资源
    有任何问题吗?
    (00) 123 456 789
    weinfoadmin@weinformatics.cn
    注册登录
    恒诺新知
    • 主页
    • 课程

      关于课程

      • 课程归档
      • 成为一名讲师
      • 讲师信息
      同等学历教学

      同等学历教学

      免费
      阅读更多
    • 特色
      • 展示
      • 关于我们
      • 问答
    • 事件
    • 个性化
    • 博客
    • 联系
    • 站点资源

      未分类

      • 首页
      • 博客
      • 未分类
      • R代码|dplyr包的使用示例

      R代码|dplyr包的使用示例

      • 发布者 weinfoadmin
      • 分类 未分类
      • 日期 2021年9月9日
      • 评论 0评论

      专题介绍:R是一种广泛用于数据分析和统计计算的强大语言,于上世纪90年代开始发展起来。得益于全世界众多 爱好者的无尽努力,大家继而开发出了一种基于R但优于R基本文本编辑器的R Studio(用户的界面体验更好)。也正是由于全世界越来越多的数据科学社区和用户对R包的慷慨贡献,让R语言在全球范围内越来越流行。其中一些R包,例如MASS,SparkR, ggplot2,使数据操作,可视化和计算功能越来越强大。R是用于统计分析、绘图的语言和操作环境。R是属于GNU系统的一个自由、免费、源代码开放的软件,它是一个用于统计计算和统计制图的优秀工具。R作为一种统计分析软件,是集统计分析与图形显示于一体的。它可以运行于UNIX、Windows和Macintosh的操作系统上,而且嵌入了一个非常方便实用的帮助系统,相比于其他统计分析软件,R的学术性开发比较早,适合生物学和医学等学术学科的科研人员使用。

      前言

      我创建【R代码】专栏,用于分享R语言解决数据,特征和模型三方面问题的代码。这些代码片段,具有实用性和迁移性。大家可以根据实际问题做修改,变通和延展。我只是R语言代码的搬运工和传播者,大家在使用这些R代码的时候,有些什么新的启示或者问题,请留言。依托【R语言】公众号,我创建了R语言群,群友们每天都会就R语言的主题进行交流和分享。需要加入R语言群的朋友,可以扫码加我的个人微信,请备注【姓名-入群】。我诚邀你加入群,大家相互学习和共同进步。


      代码

      代码来自《r-data-science-quick-reference-master》的内容。

      dplyr包的使用例子。

      #################################
      #时间:2020-07-27
      ################################
      options(warn = -1)
      ## 加载R包
      library(tidyverse)


      iris_df <- as_tibble(iris)
      print(iris_df, n = 3)
      head(iris_df$Species)


      ## 变量选择函数select
      iris_df %>%
        select(Sepal.Length, Species) %>%
        print(n = 3)

      iris_df %>%
        select(-Species) %>%
        print(n = 3)

      iris_df %>%
        select(-Species, -Sepal.Length) %>%
        print(n = 3)


      iris_df %>%
        select(1) %>%
        print(n = 3)

      iris_df %>%
        select(1:3) %>%
        print(n = 3)

      iris_df %>%
        select(Petal.Length:Species) %>%
        print(n = 3)

      iris_df %>%
        select(starts_with("Petal")) %>%
        print(n = 3)

      iris_df %>%
        select(-starts_with("Petal")) %>%
        print(n = 3)

      iris_df %>%
        select(starts_with("Petal"), Species) %>%
        print(n = 3)

      iris_df %>%
        select(starts_with("PETAL", ignore.case = TRUE)) %>%
        print(n = 3)

      iris_df %>%
        select(starts_with("S")) %>%
        print(n = 3)

      iris_df %>%
        select(ends_with("Length")) %>%
        print(n = 3)

      iris_df %>%
        select(contains("ng")) %>%
        print(n = 3)


      df <- tribble(
        ~a1x, ~ax, ~a2x, ~b2, ~b2y, ~by,
        1, 2, 3, 4, 5, 6
      )

      df %>%
        select(matches(".*d.*")) %>%
        print(n = 3)


      df %>%
        select(matches(".+d.+")) %>%
        print(n = 3)

      iris_df %>%
        select(sepal_length = Sepal.Length,
               sepal_width = Sepal.Width) %>%
        print(n = 3)

      ## 变量重命名函数rename
      iris_df %>%
        rename(sepal_length = Sepal.Length,
               sepal_width = Sepal.Width) %>%
        print(n = 3)

      ## 去重函数distinct
      iris_df %>%
        distinct(Species)

      ## 样本选择函数filter
      iris_df %>%
        filter(Species == "setosa") %>%
        print(n = 3)

      iris_df %>%
        filter(Species == "setosa") %>%
        select(ends_with("Length"), Species) %>%
        print(n = 3)


      iris_df %>%
        filter(Species != "setosa") %>%
        distinct(Species) %>%
        print(n = 3)


      iris_df %>%
        filter(Sepal.Length > 5, Petal.Width < 0.4) %>%
        print(n = 3)

      iris_df %>%
        filter(between(Sepal.Width, 2, 2.5)) %>%
        print(n = 3)

      iris_df %>%
        filter(str_starts(Species, "v")) %>%
        print(n = 3)

      iris_df %>%
        filter(str_ends(Species, "r")) %>%
        print(n = 3)


      iris_df %>%
        select(-Species) %>%
        filter_all(any_vars(. > 5)) %>%
        print(n = 3)


      iris_df %>%
        filter_at(vars(-Species), any_vars(. > 5)) %>%
        print(n = 3)


      iris_df %>%
        filter_at(c("Petal.Length", "Sepal.Length"),
                  any_vars(. > 0)) %>%
        print(n = 3)

      iris_df %>%
        filter_at(vars(Petal.Length, Sepal.Length),
                  any_vars(. > 0)) %>%
        print(n = 3)


      iris_df %>%
        filter_if(is.numeric, all_vars(. < 5)) %>%
        print(n = 3)


      df <- tribble(
        ~A, ~B, ~C,
        1,  2,  3,
        4,  5, NA,
        11, 12, 13,
        22, 22,  1
      )
      df %>% filter_all(all_vars(. > 3))


      df %>%
        filter_if(~ all(!is.na(.)), all_vars(. > 3))


      df %>% filter_all(all_vars(is.na(.) | . > 3))


      ## 排序函数arrange
      iris_df %>%
        arrange(Petal.Length) %>%
        print(n = 5)

      iris_df %>%
        arrange(Sepal.Length, Petal.Length) %>%
        print(n = 5)

      iris_df %>%
        arrange(desc(Petal.Length)) %>%
        print(n = 5)


      df <- tribble(
        ~height, ~width,
        10,     12,
        42,     24,
        14,     12
      )


      ## 变量生成函数mutate
      df %>% mutate(area = height * width)

      cm_per_inch <-  2.54
      df %>% mutate(
        height_cm = cm_per_inch * height,
        width_cm  = cm_per_inch * width,
        area_cm   = height_cm * width_cm
      )


      df %>% mutate(cm_per_inch * height)


      ## ---- echo=FALSE, warning=FALSE------------------------------------------
      suppressPackageStartupMessages(library(units, quietly = TRUE))


      ## ------------------------------------------------------------------------
      df %>% mutate(
        height_in = units::as_units(height, "in"),
        width_in  = units::as_units(width, "in"),
        area_in   = height_in * width_in,
        height_cm = units::set_units(height_in, "cm"),
        width_cm  = units::set_units(width_in, "cm"),
        area_cm   = units::set_units(area_in, "cm^2")
      )


      ## ------------------------------------------------------------------------
      df %>% transmute(
        height_in = units::as_units(height, "in"),
        width_in  = units::as_units(width, "in"),
        area_in   = height_in * width_in,
        height_cm = units::set_units(height_in, "cm"),
        width_cm  = units::set_units(width_in, "cm"),
        area_cm   = units::set_units(area_in, "cm^2")
      )


      ## ---- error=TRUE---------------------------------------------------------
      df <- tibble(
        x = rnorm(3, mean = 12, sd = 5),
      )
      my_abs <- function(x) if (x < 0) -x else x
      df %>% mutate(my_abs(x))


      ## ------------------------------------------------------------------------
      df %>% mutate(abs(x))


      ## ------------------------------------------------------------------------
      ifelse_abs <- function(x) ifelse(x < 0, -x, x)
      df %>% mutate(ifelse_abs(x))


      ## ------------------------------------------------------------------------
      my_abs <- Vectorize(my_abs)
      df %>% mutate(my_abs(x))


      ## ------------------------------------------------------------------------
      df <- tibble(x = rnorm(100))
      df %>% 
        mutate(
          x_category = case_when(
            x - mean(x) < -2 * sd(x) ~ "small",
            x - mean(x) >  2 * sd(x) ~ "large",
            TRUE           ~ "medium"
          )
        ) %>%
        print(n = 3)


      ## ------------------------------------------------------------------------
      df <- tibble(x = rnorm(100), y = rnorm(100))
      df %>% summarise(mean_x = mean(x), mean_y = mean(y))


      ## ------------------------------------------------------------------------
      classify <- function(x) {
        case_when(
          x - mean(x) < -2 * sd(x) ~ "small",
          x - mean(x) >  2 * sd(x) ~ "large",
          TRUE           ~ "medium"
        )
      }
      df %>%
        mutate(x_category = classify(x)) %>%
        group_by(x_category) %>%
        print(n = 3)


      ## ------------------------------------------------------------------------
      df %>%
        mutate(x_category = classify(x)) %>%
        print(n = 3)


      ## ------------------------------------------------------------------------
      df %>%
        mutate(x_category = classify(x)) %>%
        group_by(x_category) %>%
        summarise(mean_x = mean(x), no_x = n())


      ## ------------------------------------------------------------------------
      df %>%
        mutate(x_category = classify(x)) %>%
        group_by(x_category) %>%
        group_vars()


      ## ------------------------------------------------------------------------
      df <- tibble(x = rnorm(100), y = rnorm(100))
      df %>%
        mutate(
          x_category = classify(x),
          y_category = classify(y)
        ) %>%
        group_by(x_category, y_category) %>%
        group_vars()


      ## ------------------------------------------------------------------------
      df %>%
        mutate(
          x_category = classify(x),
          y_category = classify(y)
        ) %>%
        group_by(x_category, y_category) %>%
        summarise(mean_x = mean(x), mean_y = mean(y))


      ## ------------------------------------------------------------------------
      df %>%
        mutate(
          x_category = classify(x),
          y_category = classify(y)
        ) %>%
        group_by(x_category) %>%
        summarise(mean_x = mean(x), mean_y = mean(y))


      ## ------------------------------------------------------------------------
      df2 <- tribble(
        ~A,      ~B,    ~C, ~D,
        "left",  "up",   2, "yes",
        "right", "up",   5, "no",
        "left",  "down", 2, "yes",
        "left",  "down", 7, "no",
        "left",  "down", 3, "no",
        "right", "up",   8, "yes",
        "right", "up",   2, "yes",
        "right", "up",   8, "no"
      )
      df2 %>% group_by(A, B) %>%
        summarise(min_c = min(C), max_c = max(C))
      df2 %>% group_by(A, B) %>%
        summarise(min_c = min(C), max_c = max(C)) %>%
        summarise(max_diff = max(max_c - min_c))
      df2 %>% group_by(A, B, D) %>%
        summarise(min_c = min(C), max_c = max(C))
      df2 %>% group_by(A, B, D) %>%
        summarise(min_c = min(C), max_c = max(C)) %>%
        summarise(max_diff = max(max_c - min_c))


      ## ------------------------------------------------------------------------
      df2 %>% group_by(A, B) %>%
        summarise(min_c = min(C), max_c = max(C))


      ## ------------------------------------------------------------------------
      df2 %>% group_by(A, B, D) %>%
        summarise(min_c = min(C), max_c = max(C)) %>%
        
        
        ## ------------------------------------------------------------------------
      df2 %>% group_by(A, B, D) %>%
        summarise(min_c = min(C), max_c = max(C)) %>%
        summarise(min_diff = min(max_c - min_c))


      ## ------------------------------------------------------------------------
      df2 %>% group_by(A, B, D) %>%
        summarise(min_c = min(C), max_c = max(C)) %>%
        ungroup() %>%
        summarise(min_diff = min(max_c - min_c))


      ## ------------------------------------------------------------------------
      df %>%
        mutate(
          x_category = classify(x),
          y_category = classify(y)
        ) %>%
        group_by(x_category) %>%
        mutate(mean_x = mean(x), mean_y = mean(y)) %>%
        print(n = 5)


      ## ------------------------------------------------------------------------
      df %>%
        mutate(
          x_category = classify(x),
          y_category = classify(y)
        ) %>%
        mutate(mean_x = mean(x), mean_y = mean(y))


      ## ------------------------------------------------------------------------
      df %>%
        mutate(
          x_category = classify(x),
          y_category = classify(y)
        ) %>%
        group_by(x_category) %>%
        mutate(mean_x = mean(x), mean_y = mean(y))


      ## ------------------------------------------------------------------------
      df %>%
        mutate(
          x_category = classify(x),
          y_category = classify(y)
        ) %>%
        mutate(mean_y = mean(y)) %>%
        group_by(x_category) %>%
        mutate(mean_x = mean(x)) %>%
        distinct(mean_x, mean_y)


      ## ------------------------------------------------------------------------
      df %>%
        mutate(
          x_category = classify(x),
          y_category = classify(y)
        ) %>%
        group_by(x_category) %>%
        mutate(mean_x = mean(x)) %>%
        group_by(y_category) %>%
        mutate(mean_y = mean(y)) %>%
        distinct(
          x_category, mean_x,
          y_category, mean_y
        )


      ## ------------------------------------------------------------------------
      df1 <- tibble(
        A = paste0("a", 1:2),
        B = paste0("b", 1:2)
      )
      df2 <- tibble(
        A = paste0("a", 3:4),
        B = paste0("b", 3:4)
      )
      df3 <- tibble(
        C = paste0("c", 1:2),
        D = paste0("d", 1:2)
      )
      bind_rows(df1, df2)
      bind_cols(df1, df3)


      ## ------------------------------------------------------------------------
      grades_maths <- tribble(
        ~name,            ~grade,
        "Marko Polo",     "D",
        "Isaac Newton",   "A+",
        "Charles Darwin", "B"
      )
      grades_biology <- tribble(
        ~name,            ~grade,
        "Marko Polo",     "F",
        "Isaac Newton",   "D",
        "Charles Darwin", "A+"
      )

      inner_join(grades_maths, grades_biology, by = "name")


      ## ------------------------------------------------------------------------
      grades_maths2 <- tribble(
        ~name,            ~grade,
        "Marko Polo",     "D",
        "Isaac Newton",   "A+", # so good at physics
        "Isaac Newton",   "A+", # that he got an A+ twice
        "Charles Darwin", "B"
      )
      grades_biology2 <- tribble(
        ~name,            ~grade,
        "Marko Polo",     "F",
        "Isaac Newton",   "D",
        "Charles Darwin", "A+", # so good at biology that we
        "Charles Darwin", "A+"  # listed him twice
      )
      inner_join(grades_maths2, grades_biology2, by = "name")
      inner_join(grades_maths2, grades_biology2, by = "grade")


      ## ------------------------------------------------------------------------
      inner_join(grades_maths2, grades_biology2, by = "grade") %>%
        distinct()


      ## ------------------------------------------------------------------------
      inner_join(
        grades_maths, grades_biology,
        by = "name", suffix = c(".maths", ".biology")
      )


      ## ------------------------------------------------------------------------
      grades_geography <- tribble(
        ~name,            ~grade,
        "Marko Polo",     "A",
        "Charles Darwin", "A",
        "Immanuel Kant",  "A+"
      )
      grades_physics <- tribble(
        ~name,            ~grade,
        "Isaac Newton",    "A+",
        "Albert Einstein", "A+",
        "Charles Darwin",  "C"
      )

      inner_join(
        grades_geography, grades_physics,
        by = "name", suffix = c(".geography", ".physics")
      )


      ## ------------------------------------------------------------------------
      full_join(
        grades_geography, grades_physics,
        by = "name", suffix = c(".geography", ".physics")
      )


      ## ------------------------------------------------------------------------
      left_join(
        grades_geography, grades_physics,
        by = "name", suffix = c(".geography", ".physics")
      )
      right_join(
        grades_maths, grades_physics,
        by = "name", suffix = c(".maths", ".physics")
      )


      ## ------------------------------------------------------------------------
      semi_join(
        grades_maths2, grades_biology2,
        by = "name", suffix = c(".geography", ".physics")
      )


      ## ------------------------------------------------------------------------
      inner_join(
        grades_maths2, grades_biology2,
        by = "name", suffix = c(".geography", ".physics")
      ) %>% select(1:2)


      ## ------------------------------------------------------------------------
      anti_join(
        grades_maths2, grades_physics,
        by = "name", suffix = c(".geography", ".physics")
      )


      ## ------------------------------------------------------------------------
      grades <- list(
        grades_maths, grades_biology,
        grades_geography, grades_physics
      )
      grades %>%
        reduce(full_join, by = "name") %>%
        rename_at(2:5, ~ c("maths", "biology", "geography", "physics"))


      ## ------------------------------------------------------------------------
      mean_income <- tribble(
        ~country,  ~`2002`, ~`2003`, ~`2004`, ~`2005`,
        "Numenor",  123456,  132654,      NA,  324156,
        "Westeros", 314256,  NA,          NA,  465321,
        "Narnia",   432156,  NA,          NA,      NA,
        "Gondor",   531426,  321465,  235461,  463521,
        "Laputa",    14235,   34125,   45123,   51234,
      )


      ## ------------------------------------------------------------------------
      mean_income %>%
        gather(
          key = "year",
          value = "mean_income",
          -country
        ) %>% group_by(
          country
        ) %>% mutate(
          mean_per_country = mean(mean_income, na.rm = TRUE),
          mean_income = ifelse(
            is.na(mean_income),
            mean_per_country,
            mean_income
          )
        ) %>% spread(key = "year", value = "mean_income")


      ## ------------------------------------------------------------------------
      mean_income %>%
        gather(
          key = "year",
          value = "mean_income",
          -country
        )


      ## ------------------------------------------------------------------------
      mean_income %>%
        gather(
          key = "year",
          value = "mean_income",
          -country
        ) %>% group_by(
          country
        ) %>% summarise(
          per_country_mean = mean(mean_income, na.rm = TRUE)
        )


      ## ------------------------------------------------------------------------
      mean_income %>%
        gather(
          key = "year",
          value = "mean_income",
          -country
        ) %>% group_by(
          country
        ) %>% mutate(
          mean_per_country = mean(mean_income, na.rm = TRUE)
        ) 


      ## ------------------------------------------------------------------------
      mean_income %>%
        gather(
          key = "year",
          value = "mean_income",
          -country
        ) %>% group_by(
          country
        ) %>% mutate(
          mean_per_country = mean(mean_income, na.rm = TRUE)
        ) %>% ungroup(
        ) %>% mutate(
          mean_income = ifelse(
            is.na(mean_income),
            mean_per_country,
            mean_income
          )
        ) %>% spread(key = "year", value = "mean_income")



      温馨提示:

      第一步:运行一边代码,掌握相应的包和函数使用

      第二步:迁移到自己的数据集,进行应用


      代码的使用,有什么问题,请留言。

      请关注“恒诺新知”微信公众号,感谢“R语言“,”数据那些事儿“,”老俊俊的生信笔记“,”冷🈚️思“,“珞珈R”,“生信星球”的支持!

      • 分享:
      作者头像
      weinfoadmin

      上一篇文章

      分享就是收获
      2021年9月9日

      下一篇文章

      PDFMV框架
      2021年9月9日

      你可能也喜欢

      2-1675088548
      lncRNA和miRNA生信分析系列讲座免费视频课和课件资源包,干货满满
      30 1月, 2023
      9-1675131201
      如何快速批量修改 Git 提交记录中的用户信息
      26 1月, 2023
      8-1678501786
      肿瘤细胞通过改变CD8+ T细胞中的丙酮酸利用和琥珀酸信号来调控抗肿瘤免疫应答。
      7 12月, 2022

      留言 取消回复

      要发表评论,您必须先登录。

      搜索

      分类

      • R语言
      • TCGA数据挖掘
      • 单细胞RNA-seq测序
      • 在线会议直播预告与回放
      • 数据分析那些事儿分类
      • 未分类
      • 生信星球
      • 老俊俊的生信笔记

      投稿培训

      免费

      alphafold2培训

      免费

      群晖配置培训

      免费

      最新博文

      Nature | 单细胞技术揭示衰老细胞与肌肉再生
      301月2023
      lncRNA和miRNA生信分析系列讲座免费视频课和课件资源包,干货满满
      301月2023
      如何快速批量修改 Git 提交记录中的用户信息
      261月2023
      logo-eduma-the-best-lms-wordpress-theme

      (00) 123 456 789

      weinfoadmin@weinformatics.cn

      恒诺新知

      • 关于我们
      • 博客
      • 联系
      • 成为一名讲师

      链接

      • 课程
      • 事件
      • 展示
      • 问答

      支持

      • 文档
      • 论坛
      • 语言包
      • 发行状态

      推荐

      • iHub汉语代码托管
      • iLAB耗材管理
      • WooCommerce
      • 丁香园论坛

      weinformatics 即 恒诺新知。ICP备案号:粤ICP备19129767号

      • 关于我们
      • 博客
      • 联系
      • 成为一名讲师

      要成为一名讲师吗?

      加入数以千计的演讲者获得100%课时费!

      现在开始

      用你的站点账户登录

      忘记密码?

      还不是会员? 现在注册

      注册新帐户

      已经拥有注册账户? 现在登录

      close
      会员购买 你还没有登录,请先登录
      • ¥99 VIP-1个月
      • ¥199 VIP-半年
      • ¥299 VIP-1年
      在线支付 激活码

      立即支付
      支付宝
      微信支付
      请使用 支付宝 或 微信 扫码支付
      登录
      注册|忘记密码?