如何使用dplyr对选定的列执行算术运算

时间:2017-07-31 09:20:08

标签: r dplyr

我有以下数据框:

df <- structure(list(gene_id = c("ATP1B1", "CYCS", "DDX5", "GNB2L1", 
"PRR11"), BoneMarrow = c(0, 0, 0, 31138, 2703), Pulmonary = c(3380, 
21223.3333333333, 0, 0, 0), Umbilical = c(233, 0, 15397, 0, 0
)), .Names = c("gene_id", "BoneMarrow", "Pulmonary", "Umbilical"
), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-5L), vars = "gene_id", labels = structure(list(gene_id = c("ATP1B1", 
"CYCS", "DDX5", "GNB2L1", "PRR11")), class = "data.frame", row.names = c(NA, 
-5L), vars = "gene_id", drop = TRUE, .Names = "gene_id"), indices = list(
    0L, 1L, 2L, 3L, 4L), drop = TRUE, group_sizes = c(1L, 1L, 
1L, 1L, 1L), biggest_group_size = 1L)
df

看起来像这样:

# A tibble: 5 x 4
# Groups:   gene_id [5]
  gene_id BoneMarrow Pulmonary Umbilical
    <chr>      <dbl>     <dbl>     <dbl>
1  ATP1B1          0   3380.00       233
2    CYCS          0  21223.33         0
3    DDX5          0      0.00     15397
4  GNB2L1      31138      0.00         0
5   PRR11       2703      0.00         0

我可以使用基本方法执行以下操作:

ndf <- as.data.frame(df)
rownames(ndf) <- df$gene_id
ndf$gene_id <- NULL
ndf <- ndf + 1
ndf 

得到这个:

       BoneMarrow Pulmonary Umbilical
ATP1B1          1   3381.00       234
CYCS            1  21224.33         1
DDX5            1      1.00     15398
GNB2L1      31139      1.00         1
PRR11        2704      1.00         1

我怎么能用dplyr链做到这一点?

2 个答案:

答案 0 :(得分:2)

我们可以做到

df %>% 
  mutate_at(vars(-one_of('gene_id')), funs(.+1))  %>%
  as.data.frame() %>% 
  `row.names<-`(.[[1]]) %>% 
  select(-1)
#          BoneMarrow Pulmonary Umbilical
#ATP1B1          1   3381.00       234
#CYCS            1  21224.33         1
#DDX5            1      1.00     15398
#GNB2L1      31139      1.00         1
#PRR11        2704      1.00         1

答案 1 :(得分:2)

您可以使用tibble定位并向所有数字变量添加1。然后可以在将tibble转换为数据帧之后应用column_to_rownames函数library(tidyverse) df %>% mutate_if(is.numeric, funs(. + 1)) %>% as.data.frame() %>% column_to_rownames(var = 'gene_id') ,即

      BoneMarrow Pulmonary Umbilical
ATP1B1          1   3381.00       234
CYCS            1  21224.33         1
DDX5            1      1.00     15398
GNB2L1      31139      1.00         1
PRR11        2704      1.00         1

由此给出,

Sign(json, private) -> signedDocument