r中的表要加权 [英] Table in r to be weighted

查看:121
本文介绍了r中的表要加权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行交叉表/列联表,但需要通过加权变量对其进行加权。
这是一些样本数据。

  set.seed(123)
sex<-sample(c(';男,女),100,替换= TRUE)
年龄<-sample(c( 0-15, 16-29, 30-44, 45+),100,replace = TRUE)
wgt<-sample(c(1:10),100,replace = TRUE)
df<-data.frame(age,sex ,wgt)

我已经运行过此程序以获得常规的交叉表

  table(df $ sex,df $ age)

以获得加权频率,我尝试了Hmisc软件包(如果您知道更好的软件包,请告诉我)

  library(Hmisc)
wtd.table(df $ sex,df $ age,weights = df $ wgt)
match.arg(type)中的错误:'arg'的长度必须为1

我不确定我哪里出了问题,但是它没有运行,因此任何帮助都会很大。
或者,如果您知道如何在另一个程序包中执行此操作,那么这对于分析调查数据可能会更好,那也很好。

解决方案

尝试一下

  GDAtools :: wtable(df $ sex,df $ age,w = df $ wgt)

输出

  0-15 16-29 30-44 45+ NA tot 
女56 73 60 76 0265
男76 99106 90 0371
不适用0 0 0 0 0 0
tot 132172166166 0636

更新


如果您不想安装整个软件包,则需要两个基本功能:


< a href = https://rdrr.io/cran/GDAtools/src/R/dichotom.R rel = nofollow noreferrer> wtable 和二分法


获取它们,您应该可以使用毫无问题

I'm trying to run a crosstab/contingency table, but need it weighted by a weighting variable. Here is some sample data.

set.seed(123)
sex <- sample(c("Male", "Female"), 100, replace = TRUE)
age <- sample(c("0-15", "16-29", "30-44", "45+"), 100, replace = TRUE)
wgt <- sample(c(1:10), 100, replace = TRUE)
df <- data.frame(age,sex, wgt)

I've run this to get a regular crosstab table

table(df$sex, df$age)

to get a weighted frequency, I tried the Hmisc package (if you know a better package let me know)

library(Hmisc)
wtd.table(df$sex, df$age, weights=df$wgt)
Error in match.arg(type) : 'arg' must be of length 1

I'm not sure where I've gone wrong, but it doesn't run, so any help will be great. Alternatively, if you know how to do this in another package, which may be better for analysing survey data, that would be great too. Many thanks in advance.

解决方案

Try this

GDAtools::wtable(df$sex, df$age, w = df$wgt)

Output

       0-15 16-29 30-44 45+ NA tot
Female   56    73    60  76  0 265
Male     76    99   106  90  0 371
NA        0     0     0   0  0   0
tot     132   172   166 166  0 636

Update

In case you do not want to install the whole package, here are two essential functions you need:

wtable and dichotom

Source them and you should be able to use wtable without any problem.

这篇关于r中的表要加权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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