hardikudeshi
hardikudeshi

Reputation: 1491

How to cross-tabulate two variables in 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  

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

Upvotes: 3

Views: 2008

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81743

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

Upvotes: 8

Related Questions