在 R 中创建按列值分组的 Z-Score [英] Creating Z-Score grouped by column value in R

查看:87
本文介绍了在 R 中创建按列值分组的 Z-Score的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 R 中是否有一种简单的方法来创建按列值分组的 Z 分数列.

I was wondering if there was an easy way in R to create a Z-score column grouped by a column value.

例如,像这样转动一个数据框

For example, turning a dataframe like this

  Obs      Year          Dollars
   1       1960            2
   2       1960            3
   3       1960            5
   4       1960            6
   5       1961           15
   6       1961           20 
   7       1961           25
   8       1961           40

变成这样

  Obs      Year          Dollars     Z-Score
   1       1960            2         -1.265
   2       1960            3         -0.633
   3       1960            5          0.633
   4       1960            6          1.266
   5       1961           15         -1.069
   6       1961           20         -0.535
   7       1961           25          0
   8       1961           40          1.604

样本按年份分隔的地方

推荐答案

base R中很简单,使用ave即可.

In base Rit's very simple, just use ave.

dat$Z.Score <- ave(dat$Dollars, dat$Year, FUN = scale)
dat
#  Obs Year Dollars    Z.Score
#1   1 1960       2 -1.0954451
#2   2 1960       3 -0.5477226
#3   3 1960       5  0.5477226
#4   4 1960       6  1.0954451
#5   5 1961      15 -0.9258201
#6   6 1961      20 -0.4629100
#7   7 1961      25  0.0000000
#8   8 1961      40  1.3887301

数据.

dat <-
structure(list(Obs = 1:8, Year = c(1960L, 1960L, 1960L, 1960L, 
1961L, 1961L, 1961L, 1961L), Dollars = c(2L, 3L, 5L, 6L, 15L, 
20L, 25L, 40L)), .Names = c("Obs", "Year", "Dollars"), class = "data.frame", row.names = c(NA, 
-8L))

编辑.
在评论中与 akrun 讨论之后,我将使用包 data.table 发布他的解决方案.结果是一样的,只是结果的类不同,dat变成了data.table类的对象.

EDIT.
Following the discussion with akrun in the comments, I will post his solution using package data.table. The result is the same, only the class of the result is different, dat becomes an object of class data.table.

library(data.table)

setDT(dat)[, Z.Score := scale(Dollars), Year]

这篇关于在 R 中创建按列值分组的 Z-Score的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆