我有以下数据框架:
df<- splitstackshape::stratified(iris, group="Species", size=1)我想为每个物种做一个z评分,包括所有的变量。我可以手动地为每一行找到SD和平均值,并使用适当的公式,但是我需要重复几次,并且希望找到一种更有效的方法。
我试过使用scale(),但无法弄清楚如何让它执行包含多个变量和分组变量的逐行计算。
使用dplyr::group_by返回"'x‘必须是数值变量“错误。
发布于 2022-02-27 21:52:48
你确定问题是给每个小组取个z分吗?应该是每一种价值。
让我们说,z得分的函数可以是:
scale(x, center = TRUE, scale = TRUE)或
function_zscore = function(x){x <- x[na.rm = TRUE]; return(((x) - mean(x)) / sd(x))}这两个函数都表明,如果参数x是向量,结果也将返回到向量。
df<- splitstackshape::stratified(iris, group="Species", size=1)
df <- tidyr::pivot_longer(df, cols = c(1:4), names_to = "var.name", values_to = "value")
df %>%
group_by(Species) %>%
mutate(zscore = scale(value, center = TRUE, scale = TRUE)[,1])
## A tibble: 12 x 4
## Groups: Species [3]
# Species var.name value zscore
# <fct> <chr> <dbl> <dbl>
# 1 setosa Sepal.Length 4.9 1.22
# 2 setosa Sepal.Width 3.1 0.332
# 3 setosa Petal.Length 1.5 -0.455
# 4 setosa Petal.Width 0.2 -1.09
# 5 versicolor Sepal.Length 5.9 1.10
# 6 versicolor Sepal.Width 3.2 -0.403
# 7 versicolor Petal.Length 4.8 0.486
# 8 versicolor Petal.Width 1.8 -1.18
# 9 virginica Sepal.Length 6.5 1.14
#10 virginica Sepal.Width 3 -0.574
#11 virginica Petal.Length 5.2 0.501
#12 virginica Petal.Width 2 -1.06 如果我们仍然希望每一组得到一个分数来描述一个样本是如何偏离平均值的,那么一个可能的解决办法就是得到变异系数?
df %>%
group_by(Species) %>%
summarise(coef.var = 100*sd(value)/mean(value))
## A tibble: 3 x 2
# Species coef.var
# <fct> <dbl>
#1 setosa 83.8
#2 versicolor 45.8
#3 virginica 49.0https://stackoverflow.com/questions/71287051
复制相似问题