R:使用循环产生的计数表或列联表 [英] R: Count or contingency tables produced using a loop

查看:54
本文介绍了R:使用循环产生的计数表或列联表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 编程的新手,所以我正在寻求帮助以开始我的工作.我有一个包含4列的长"数据集(我之前在R中将其重塑了):

I am new to programming in R so I looking for help to start me off. I have a "long" dataset with 4 columns (which I reshaped earlier in R):

d=matrix(c(1,2,3,4,5,6,7,"A","A","A","B","B","B","B",0,0,99,0,0,99,0,99,0,99,99,0,0,99), ncol=4)
colnames(d) = c("ID","S.ID","ValA","ValB"); dt=as.table(d)

我想为每个S.ID(即A和B)分别创建一个ValA和ValB计数的列联表.

I'd like to create, for each S.ID separately (ie A and B), a contingency table for counts of ValA and ValB

例如(在这里)-

在我的实际示例中,我有17个S.ID,并且我想编写一个程序来为每个S.ID生成列联表.

In my actual example I have 17 S.IDs and I'd like to write a program that will generate the contingency tables for each of these.

此外,在R Studio中这样做会更容易吗?如果是这样,请您能详细说明一下吗?

Additionally, Will this be easier to do in R Studio? If so, please can you also detail how?

非常感谢!

-感谢所有如此坦率地回答的人!:)

-Thanks to all who answered so prompltly! :)

推荐答案

您可以对多个变量使用 table :

You can use table on multiple variables:

with(as.data.frame(d), table(ValA, ValB, S.ID))

# , , S.ID = A
#    ValB
#ValA 0 99
#  0  1  1
#  99 0  1

#, , S.ID = B
#    ValB
#ValA 0 99
#  0  1  2
#  99 1  0

这篇关于R:使用循环产生的计数表或列联表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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