gpt4 book ai didi

r - 如何收集然后变异一个新列然后再次传播到宽格式

转载 作者:行者123 更新时间:2023-12-04 10:10:32 24 4
gpt4 key购买 nike

使用 tidyr/dplyr,我有一些因子列,我想对其进行 Z 评分,然后对平均 Z 评分进行变异,同时保留原始数据以供引用。

我想避免在 tidyr/dplyr 中使用 for 循环,因此我正在收集数据并在单个列上执行计算(Z 分数)。但是,我正在努力恢复宽格式。

这是一个 MWE:

library(dplyr)
library(tidyr)

# Original Data
dfData <- data.frame(
Name = c("Steve","Jwan","Ashley"),
A = c(10,20,12),
B = c(0.2,0.3,0.5)
) %>% tbl_df()

# Gather to Z-score
dfLong <- dfData %>% gather("Factor","Value",A:B) %>%
mutate(FactorZ = paste0("Z_",Factor)) %>%
group_by(Factor) %>%
mutate(ValueZ = (Value - mean(Value,na.rm = TRUE))/sd(Value,na.rm = TRUE))

# Now go wide to do some mutations (eg Z)Avg = (Z_A + Z_B)/2)

# This does not work
dfWide <- dfLong %>%
spread(Factor,Value) %>%
spread(FactorZ,ValueZ)%>%
mutate(Z_Avg = (Z_A+Z_B)/2)


# This is the desired result
dfDesired <- dfData %>% mutate(Z_A = (A - mean(A,na.rm = TRUE))/sd(A,na.rm = TRUE)) %>% mutate(Z_B = (B - mean(B,na.rm = TRUE))/sd(B,na.rm = TRUE)) %>%
mutate(Z_Avg = (Z_A+Z_B)/2)

感谢您的帮助/输入!

最佳答案

另一种使用dplyr(版本 0.5.0)的方法

library(dplyr)

dfData %>%
mutate_each(funs(Z = scale(.)), -Name) %>%
mutate(Z_Avg = (A_Z+B_Z)/2)

关于r - 如何收集然后变异一个新列然后再次传播到宽格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38260716/

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