按多列创建双向表

时间:2017-11-10 16:50:44

标签: r

我的数据如下。我想创建一个双向表,我可以轻松创建它。

start_city=c("a","b","a")
end_city=c("b","a","a")
travel=data.frame(start_city,end_city)
table(start_city,end_city)

现在我想在我的双向表中添加一个状态。我怎么能这样做

start_city=c("a","b","a")
end_city=c("b","a","a")
start_state=c("x","y","x")
end_state=c("y","x","x")
travel=data.frame(start_city,start_state,end_city,end_state)

UPDATE1

table(do.call(paste, travel[1:2]), do.call(paste, travel[3:4])) 由akrun给出以下作品 但是,在生成的数据框架中,有一种简单的方法可以将最左侧列和顶部列的内容分隔为,吗?现在,最左边的列和顶部列具有状态和城市的连接。

1 个答案:

答案 0 :(得分:1)

我偶然发现了这个包裹。这类似于SAS PROC FREQ中的三向表。希望这会有所帮助。

source("http://pcwww.liv.ac.uk/~william/R/crosstab.r")
crosstab(travel, row.vars = c("start_state", "start_city"), col.vars = c("end_state","end_city"), type = "f")