r中的表要加权 [英] Table in r to be weighted
问题描述
我正在尝试运行交叉表/列联表,但需要通过加权变量对其进行加权。
这是一些样本数据。
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. I've run this to get a regular crosstab table to get a weighted frequency, I tried the Hmisc package (if you know a better package let me know) 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 Output Update In case you do not want to install the whole package, here are two essential functions you need: Source them and you should be able to use 这篇关于r中的表要加权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!毫无问题
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)
table(df$sex, df$age)
library(Hmisc)
wtd.table(df$sex, df$age, weights=df$wgt)
Error in match.arg(type) : 'arg' must be of length 1
GDAtools::wtable(df$sex, df$age, w = df$wgt)
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
wtable
without any problem.