问题
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