使用R,如何旋转/转换其元素是函数结果的数据集 [英] Using R, how to pivot/transform a dataset whose elements are the result of a function

查看:68
本文介绍了使用R,如何旋转/转换其元素是函数结果的数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下玩具数据集:

z <- c(2,2,3,3,3,4,2,2)
y <- c(6,6,6,5,4,6,6,5)
x <- c(1,1,2,3,5,4,4,3)
df <- cbind(x,y,z)

我想弄清楚一个元素z与每个元素y一起出现x个元素x的次数.结果数据集应如下所示:

I would like to figure out how many times an element z appears with an element x for each element y. The resulting dataset should look like the following:

     y(4) y(5) y(6)
x(1)  0    0    2
x(2)  0    0    1 
x(3)  0    2    0
x(4)  0    0    2
x(5)  1    0    0

该解决方案必须具有可扩展性,以使x,y和z中的元素数量无关.

The solution needs to be scalable such that the number of elements in x,y, and z is irrelevant.

推荐答案

您想要的结果只是xytable.

Your desired result is just a table of x and y.

> table(df[,"x"], df[,"y"])
#   
#    4 5 6
#  1 0 0 2
#  2 0 0 1
#  3 0 2 0
#  4 0 0 2
#  5 1 0 0

也许将df转换为data.frame可能更有意义

Maybe converting df to a data.frame might make more sense

> df <- data.frame(df)
> with(df, table(x, y))
#    y
# x   4 5 6
#   1 0 0 2
#   2 0 0 1
#   3 0 2 0
#   4 0 0 2
#   5 1 0 0

这篇关于使用R,如何旋转/转换其元素是函数结果的数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆