gpt4 book ai didi

r - 使用 mutate 创建行而不是列

转载 作者:行者123 更新时间:2023-12-05 09:04:50 26 4
gpt4 key购买 nike

一些数据:

webdata %>% dput
structure(list(`2021-01-01` = c(9769.77145143346, 240.374021734625
), `2021-01-02` = c(9747.83506410782, 205.305063093191), `2021-01-03` = c(10244.2824708895,
253.285005879351), `2021-01-04` = c(9903.98090317497, 250.068739190171
), `2021-01-05` = c(10126.8521068156, 152.172995948704), Total = c(sessions = 49792.7219964214,
conversions = 1101.20582584604)), class = "data.frame", row.names = c("sessions",
"conversions"))

看起来像这样:

webdata
2021-01-01 2021-01-02 2021-01-03 2021-01-04 2021-01-05 Total
sessions 9769.771 9747.8351 10244.282 9903.9809 10126.852 49792.722
conversions 240.374 205.3051 253.285 250.0687 152.173 1101.206

我想添加一行 ConversionRate,即 conversions/sessions。这就像转置 dplyr 操作,因为我需要行突变。

我该怎么做才能让 ConversionRate 有一个新行,即 conversions/sessions

最佳答案

已更新如果您想使用行名而不是​​索引来执行操作,我认为此解决方案可能对您的原始数据集有帮助:

library(dplyr)
library(tibble)

df %>%
summarise(across(everything(), ~ (.x)[which(rownames(df) == "sessions")]/
.x[which(rownames(df) == "conversions")]),
rowname = 'ConversionRate') %>%
bind_rows(df %>%
rownames_to_column()) %>%
column_to_rownames("rowname")

2021-01-01 2021-01-02 2021-01-03 2021-01-04 2021-01-05 Total
ConversionRate 40.64404 47.47976 40.44567 39.60503 66.54829 45.21654
sessions 9769.77145 9747.83506 10244.28247 9903.98090 10126.85211 49792.72200
conversions 240.37402 205.30506 253.28501 250.06874 152.17300 1101.20583

关于r - 使用 mutate 创建行而不是列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68143652/

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