How to cross-tabulate two variables in R?

后端 未结 1 836
悲&欢浪女
悲&欢浪女 2021-01-20 09:37

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

1条回答
  •  盖世英雄少女心
    2021-01-20 10:18

    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
    

    0 讨论(0)
提交回复
热议问题