How to cross-tabulate two variables in R?

孤街醉人 提交于 2019-12-20 02:38:13

问题


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  

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.

Output of sample data:

"","1","2"
"1",0,1
"2",1,0
"3",1,0

回答1:


The data:

df <- read.table(text = "1 2 
2 1 
3 1")

Calculate frequencies using table:

(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 data with the function write.csv:

write.csv(tab, "tab.csv")

The resulting file:

"","1","2"
"1",0,1
"2",1,0
"3",1,0


来源:https://stackoverflow.com/questions/14143185/how-to-cross-tabulate-two-variables-in-r

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