繁体   English   中英

使用 mutate_all 将所有列除以选定的列

[英]Divide all columns by a chosen column using mutate_all

我有一个看起来像这样的示例数据框(我的完整数据框有“d”加上 57 个元素):

d <- seq(0, 100, 0.5) 
Fe <- runif(201, min = 0, max = 1000) 
Ca <- runif(201, min = 0, max = 1000) 
Zr <- runif(201, min = 0, max = 1000) 
Ti <- runif(201, min = 0, max = 1000) 
Al <- runif(201, min = 0, max = 1000) 
example <- data.frame(d, Fe, Ca, Zr, Ti, Al)
Ratio_Elements <- c("Fe", "Ti", "Zr", "d") #this subset of the 
dataframe is user defined
Detrital_Divisor <- "Zr"

Detrital_Divisor 可以根据用户输入进行更改,但始终是“示例”数据框中的一列。 我想将所有剩余的列除以 Detrital_Divisor 列,最好使用管道。 现在我有:

Example_Ratio <- example %>%
select (Ratio_Elements) #to subset to the user selected elements
mutate_all(./Detrital_Divisor)

但我收到错误:

Error in Ops.data.frame(., Detrital_Divisor) : 
  ‘/’ only defined for equally-sized data frames.

我也试过:

Example_Ratio <- example %>%
select (Ratio_Elements)
sweep(., Detrital_Divisor, MARGIN = 1, '/')

基于在此论坛上提出的类似问题,但我无法让它发挥作用。 我收到错误

    `Error in Ops.data.frame(x, aperm(array(STATS, dims[perm]), order(perm)),  : 
  list of length 206340 not meaningful.`

我知道这个问题有些重复,但我发现的其他答案在我的情况下不起作用。 我的整个数据框有 57 个元素,因此编写代码来单独划分每一列会很长。

提前感谢您的任何建议。

可能是这样的:

library(tidyverse)

d <- seq(0, 100, 0.5) 
Fe <- runif(201, min = 0, max = 1000) 
Ca <- runif(201, min = 0, max = 1000) 
Zr <- runif(201, min = 0, max = 1000) 
Ti <- runif(201, min = 0, max = 1000) 
Al <- runif(201, min = 0, max = 1000) 
example <- data.frame(d, Fe, Ca, Zr, Ti, Al)
Ratio_Elements <- c("Fe", "Ti", "Zr", "d") #this subset of the 

Example_Ratio <- example %>%
  mutate_at(vars(-Zr), funs(. / Zr)) %>%
  select(Ratio_Elements)

我知道你说你想看到一个mutate_all解决方案,但我猜你不想把Zr分开?

在这种情况下mutate_at更有帮助,否则你可以做mutate_all(funs(. / Zr))

如果你想保留提到的向量:

Detrital_Divisor <- as.symbol("Zr")

Example_Ratio <- example %>%
  mutate_at(vars(- !! Detrital_Divisor), funs(. / !! Detrital_Divisor)) %>%
  select(Ratio_Elements)

更新(dplyr 0.8.0)

现在funs已废弃dplyr 0.8.0 ,您可以只使用~ ,例如:

Detrital_Divisor <- as.symbol("Zr")

Example_Ratio <- example %>%
  mutate_at(vars(- !! Detrital_Divisor), ~ . / !! Detrital_Divisor) %>%
  select(Ratio_Elements)

另一方面,还有list - 对于以多种方式变异或命名输出很有用,例如:

Example_Ratio <- example %>%
  mutate_at(vars(- !! Detrital_Divisor), list(appended_name = ~ . / !! Detrital_Divisor))

更新(dplyr 1.0.0)

作为dplyr 1.0.0 ,你可能会想使用across

Example_Ratio <- example %>%
  mutate(across(-Detrital_Divisor, ~ . / !! Detrital_Divisor)) %>%
  select(all_of(Ratio_Elements))

更新回答@arg0naut91 (dplyr 1.0.0)

Example_Ratio <- example %>% 
  mutate(across(everything()), . / Zr) %>% 
  select(Ratio_Elements)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM