如何使用dozr::mutate_all对选定列进行舍入

zy1mlcev  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(98)

我正在使用以下软件包版本

# devtools::install_github("hadley/dplyr")
> packageVersion("dplyr")
[1] ‘0.5.0.9001’

下面是一个例子:

library(dplyr)
df  <- structure(list(gene_symbol = structure(1:6, .Label = c("0610005C13Rik", 
"0610007P14Rik", "0610009B22Rik", "0610009L18Rik", "0610009O20Rik", 
"0610010B08Rik"), class = "factor"), fold_change = c(1.54037, 
1.10976, 0.785, 0.79852, 0.91615, 0.87931), pvalue = c(0.5312, 
0.00033, 0, 0.00011, 0.00387, 0.01455), ctr.mean_exp = c(0.00583, 
59.67286, 83.2847, 6.88321, 14.67696, 1.10363), tre.mean_exp = c(0.00899, 
66.22232, 65.37819, 5.49638, 13.4463, 0.97043), ctr.cv = c(5.49291, 
0.20263, 0.17445, 0.46288, 0.2543, 0.39564), tre.cv = c(6.06505, 
0.28827, 0.33958, 0.53295, 0.26679, 0.52364)), .Names = c("gene_symbol", 
"fold_change", "pvalue", "ctr.mean_exp", "tre.mean_exp", "ctr.cv", 
"tre.cv"), row.names = c(NA, -6L), class = c("tbl_df", "tbl", 
"data.frame"))

它看起来像这样:

> df
# A tibble: 6 × 7
    gene_symbol fold_change  pvalue ctr.mean_exp tre.mean_exp  ctr.cv  tre.cv
         <fctr>       <dbl>   <dbl>        <dbl>        <dbl>   <dbl>   <dbl>
1 0610005C13Rik     1.54037 0.53120      0.00583      0.00899 5.49291 6.06505
2 0610007P14Rik     1.10976 0.00033     59.67286     66.22232 0.20263 0.28827
3 0610009B22Rik     0.78500 0.00000     83.28470     65.37819 0.17445 0.33958
4 0610009L18Rik     0.79852 0.00011      6.88321      5.49638 0.46288 0.53295
5 0610009O20Rik     0.91615 0.00387     14.67696     13.44630 0.25430 0.26679
6 0610010B08Rik     0.87931 0.01455      1.10363      0.97043 0.39564 0.52364

我想四舍五入的浮动(第二列向前),以3位数。如何使用dplyr::mutate_all()
我试过这个:

cols <- names(df)[2:7]
# df <- df %>% mutate_each_(funs(round(.,3)), cols)
# Warning message:
#'mutate_each_' is deprecated.
# Use 'mutate_all' instead.
# See help("Deprecated") 

df <- df %>% mutate_all(funs(round(.,3)), cols)

但得到以下错误:

Error in mutate_impl(.data, dots) : 
  3 arguments passed to 'round'which requires 1 or 2 arguments
bt1cpqcv

bt1cpqcv1#

虽然新的across()函数比以前的mutate_if变体稍微详细一些,但dplyr 1.0.0更新使tidyverse语言和代码更加一致和通用。
这是如何舍入指定的列:
df %>% mutate(across(2:7, round, 3)) #按位置排列的第2-7列
df %>% mutate(across(cols, round, 3)) #由变量cols指定的列
以下是如何将所有数值列舍入到3位小数:
df %>% mutate(across(where(is.numeric), round, 3))
这是如何舍入所有列,但它在这种情况下不起作用,因为gene_symbol不是数值:
df %>% mutate(across(everything(), round, 3))
在我们将where(is.numeric)放入across的参数中的地方,您可以放入其他列规范,如-1-gene_symbol,以排除列1。请参阅help(tidyselect)以了解更多选项。

更新为dafer 1.0.0

across()函数替换了dplyr动词的_if/_all/_at/_each变体。https://dplyr.tidyverse.org/dev/articles/colwise.html#how-do-you-convert-existing-code
旧的答案:由于有些列不是数值型的,你可以使用mutate_if,如果(当且仅当)它是数值型的,则可以对列进行舍入:
df %>% mutate_if(is.numeric, round, 3)

jogvjijk

jogvjijk2#

packageVersion("dplyr")
[1] '0.7.6'

尝试

df %>% mutate_at(2:7, funs(round(., 3)))

It works!!

相关问题