如何交叉列出R中的两个变量? [英] How to cross-tabulate two variables in R?
问题描述
这似乎是基本的,但是我不明白.我正在尝试计算R中的频率表,如下所示
This seems to be basic, but I wont get it. I am trying to compute the frequency table in R for the data as below
1 2
2 1
3 1
我想在csv输出中传输双向频率,其行将是数据列A中的所有唯一条目,其列将是数据列B中的所有唯一条目,以及单元格值将是值出现的次数.我已经探究过table
之类的构造,但是我无法以csv格式正确输出值.
I want to transport the the two way frequencies in csv output, whose rows will be all the unique entries in column A of the data and whose columns will be all the unique entries in column B of the data, and the cell values will be the number of times the values have occurred. I have explored some constructs like table
but I am not able to output the values correctly in csv format.
示例数据的输出:
"","1","2"
"1",0,1
"2",1,0
"3",1,0
推荐答案
数据:
df <- read.table(text = "1 2
2 1
3 1")
使用table
计算频率:
(如果您的对象是矩阵,则可以在使用table
之前使用as.data.frame
将其转换为数据帧.)
(If your object is a matrix, you could convert it to a data frame using as.data.frame
before using table
.)
tab <- table(df)
V2
V1 1 2
1 0 1
2 1 0
3 1 0
使用功能write.csv
写入数据:
write.csv(tab, "tab.csv")
结果文件:
"","1","2"
"1",0,1
"2",1,0
"3",1,0
这篇关于如何交叉列出R中的两个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!