xtsum command for R?

▼魔方 西西 提交于 2020-01-23 13:11:25

问题


We're working on panel data, and there is a command in Stata, xtsum, that gives you within and between variance for the variables in the data set. Is there a similar command for R, that produces clean output?


回答1:


I have used a little function to do it.

The function XTSUM takes three inputs:

data -- the dataset
varname -- the variable to xtsum
unit -- the identifier for the within dimension

library(rlang)
library(dplyr)
XTSUM <- function(data, varname, unit) {
  varname <- enquo(varname)
  loc.unit <- enquo(unit)
ores <- data %>% summarise(ovr.mean=mean(!! varname, na.rm=TRUE), ovr.sd=sd(!! varname, na.rm=TRUE), ovr.min = min(!! varname, na.rm=TRUE), ovr.max=max(!! varname, na.rm=TRUE), ovr.N=sum(as.numeric((!is.na(!! varname)))))
bmeans <- data %>% group_by(!! loc.unit) %>% summarise(meanx=mean(!! varname, na.rm=T), t.count=sum(as.numeric(!is.na(!! varname))))
bres <- bmeans %>% ungroup() %>% summarise(between.sd = sd(meanx, na.rm=TRUE), between.min = min(meanx, na.rm=TRUE), between.max=max(meanx, na.rm=TRUE), Units=sum(as.numeric(!is.na(t.count))), t.bar=mean(t.count, na.rm=TRUE))
wdat <- data %>% group_by(!! loc.unit) %>% mutate(W.x = scale(!! varname, scale=FALSE))
wres <- wdat %>% ungroup() %>% summarise(within.sd=sd(W.x, na.rm=TRUE), within.min=min(W.x, na.rm=TRUE), within.max=max(W.x, na.rm=TRUE))
return(list(ores=ores,bres=bres,wres=wres))
}
library(haven)
nlswork <- read_stata("http://www.stata-press.com/data/r13/nlswork.dta")
XTSUM(nlswork, varname=hours, unit=idcode)


来源:https://stackoverflow.com/questions/49282083/xtsum-command-for-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!