如何使用变量作为矩阵坐标将数据帧转换为矩阵? [英] How to convert a dataframe into a matrix using variables as the coordinate of the matrix?

查看:83
本文介绍了如何使用变量作为矩阵坐标将数据帧转换为矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含3列的数据框:

I have a data frame with 3 columns:

df<-data.frame(x=c(1,1,1,2,2,2,2,3,3), y=c(1,2,3,1,2,3,4,1,2), percentage=c(50,25,25,15,35,25,25,55,45))

看起来像:

  x y percentage
1 1 1         50
2 1 2         25
3 1 3         25
4 2 1         15
5 2 2         35
6 2 3         25
7 2 4         25
8 3 1         55
9 3 2         45

第三列表示x-ID对象(1 col)中y-ID对象(2 col)的面积百分比.

The third column represents the percentage of the area of y-ID objects (2 col) that are within the x-ID objects (1 col).

我想得到一个具有x和y的矩阵(或与smthg相关),它们定义了坐标/下标以及矩阵的元素百分比".

I would like to get a matrix (or smthg related) with the x and y that define the coordinates/subscript and the "percentage", the elements of the matrix.

基本上,我想得到一个像这样的矩阵:

Basically, I would like to get a matrix like that:

  1  2  3  4
1 50 25 25 0
2 15 35 25 25
3 55 45 0  0

有没有简单的方法来实现这一目标?

Is there an easy way to achieve this ?

推荐答案

xtabs(percentage ~ x + y, data = df)

这篇关于如何使用变量作为矩阵坐标将数据帧转换为矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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