我希望获得数据中所有变量对的xtabs函数结果(其中一个变量是永久变量,另一个变量应该来自存储在数据帧中的其余变量).I知道如何一次手动执行每一对变量,但是我有很多变量,我想找到一种循环它的方法。知道我该怎么做吗?下面是一个数据框架示例:
dat <- read.table(text = " category birds wolfs snakes
yes 3 9 7
no 3 8 4
no 1 2 8
yes 1 2 3
yes 1 8 3
no 6 1 2
yes 6 7 1
no 6 1 5
yes 5 9 7
no 3 8 7
no 4 2 7
yes 1 2 3
yes 7 6 3
no 6 1 1
yes 6 3 9
no 6 1 1 ",header = TRUE)我手动地使用这一行代码来获得我所需要的:
xtabs(~category + birds, data = dat)
xtabs(~category + wolfs , data = dat)
xtabs(~category + snakes, data = dat)但是当我有很多变量时,这可能是非常没有效率的。
发布于 2014-09-23 08:03:16
尝试:
apply(dat[,2:4], 2, function(x) xtabs(~dat$category+x) )
$birds
x
dat$category 1 3 4 5 6 7
no 1 2 1 0 4 0
yes 3 1 0 1 2 1
$wolfs
x
dat$category 1 2 3 6 7 8 9
no 4 2 0 0 0 2 0
yes 0 2 1 1 1 1 2
$snakes
x
dat$category 1 2 3 4 5 7 8 9
no 2 1 0 1 1 2 1 0
yes 1 0 4 0 0 2 0 1https://stackoverflow.com/questions/25989570
复制相似问题