gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:28:27 24 4
gpt4 key购买 nike

我有一个看起来像这样的示例数据框(我的完整数据框有“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)
现在, funsdplyr 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))

关于r - 使用 mutate_all 将所有列除以选定的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54030049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com