如何使用 dplyr 扫描特定列? [英] How do I sweep specific columns with dplyr?

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

问题描述

对于我的数据类型,一个非常常见的操作是对所有列应用归一化因子.这可以使用 sweepscale 有效地完成:

An incredibly common operation for my type of data is applying a normalisation factor to all columns. This can be done efficiently using sweep or scale:

normalized = scale(data, center = FALSE, scale = factors)
# or
normalized = sweep(data, 2, factors, `/`)

哪里

data = structure(list(A = c(3L, 174L, 6L, 1377L, 537L, 173L),
    B = c(1L, 128L, 2L, 1019L, 424L, 139L),
    C = c(3L, 66L, 2L, 250L, 129L, 40L),
    D = c(4L, 57L, 4L, 251L, 124L, 38L)),
    .Names = c("A", "B", "C", "D"),
    class = c("tbl_df", "data.frame"), row.names = c(NA, -6L))

factors = c(A = 1, B = 1.2, C = 0.8, D = 0.75)

但是,当我的数据前面有附加列时,如何使用 dplyr 执行此操作?我可以在单独的语句中完成,但我希望在 one 管道中完成.这是我的数据:

However, how do I do this with dplyr, when my data has additional columns in front? I can do it in separate statements, but I’d like doing it in one pipeline. This is my data:

data = structure(list(ID = c(1, 2, 3, 4, 5, 6),
    Type = c("X", "X", "X", "Y", "Y", "Y"),
    A = c(3L, 174L, 6L, 1377L, 537L, 173L),
    B = c(1L, 128L, 2L, 1019L, 424L, 139L),
    C = c(3L, 66L, 2L, 250L, 129L, 40L),
    D = c(4L, 57L, 4L, 251L, 124L, 38L)),
    .Names = c("ID", "Type", "A", "B", "C", "D"),
    class = c("tbl_df", "data.frame"), row.names = c(NA, -6L))

我想在不触及前两列的情况下改变数据列.通常我可以用 mutate_each 做到这一点;但是,我如何无法将标准化因子传递给该函数:

And I’d like to mutate the data columns without touching the first two columns. Normally I can do this with mutate_each; however, how I cannot pass my normalisation factors to that function:

data %>% mutate_each(funs(. / factors), A:D)

不出所料,这假设我想将每一列除以factors,而不是每一列除以其匹配因数.

This, unsurprisingly, assumes that I want to divide each column by factors, rather than each column by its matching factor.

推荐答案

dplyr 1.0.0开始,你可以:

data %>%
 rowwise() %>%
 mutate(across(A:D)/factors)

     ID Type      A       B      C      D
  <dbl> <chr> <dbl>   <dbl>  <dbl>  <dbl>
1     1 X         3   0.833   3.75   5.33
2     2 X       174 107.     82.5   76   
3     3 X         6   1.67    2.5    5.33
4     4 Y      1377 849.    312.   335.  
5     5 Y       537 353.    161.   165.  
6     6 Y       173 116.     50     50.7 

这篇关于如何使用 dplyr 扫描特定列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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