将dataFrame转换为R中的二进制数据框
我有一个数据框,例如
Groups Names
G1 SP1
G1 SP2
G1 SP3
G2 SP1
G2 SP4
G3 SP2
G3 SP1
,我想将其转换为:
Names G1 G2 G3
SP1 1 1 1
SP2 1 0 1
SP3 1 0 0
SP4 0 1 0
列中的组中的位置
在单元格中 1 =存在和 0 =不存在
这是dput格式
structure(list(Groups = c("G1", "G1", "G1", "G2", "G2", "G3",
"G3"), Names = c("SP1", "SP2", "SP3", "SP1", "SP4", "SP2", "SP1"
)), class = "data.frame", row.names = c(NA, -7L))
I have a dataframe such as
Groups Names
G1 SP1
G1 SP2
G1 SP3
G2 SP1
G2 SP4
G3 SP2
G3 SP1
And I would like to transform it as :
Names G1 G2 G3
SP1 1 1 1
SP2 1 0 1
SP3 1 0 0
SP4 0 1 0
Where in columns are the Groups
and within cell 1 = present and 0 = absent
Here is the dput format
structure(list(Groups = c("G1", "G1", "G1", "G2", "G2", "G3",
"G3"), Names = c("SP1", "SP2", "SP3", "SP1", "SP4", "SP2", "SP1"
)), class = "data.frame", row.names = c(NA, -7L))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
表
:Use
table
:将评论扩展到答案。
这被称为应变表,可以通过几种方式计算,而无需使用精美的软件包。
这样的表是矩阵。如果您想要一个数据框架,请使用以下方式使用:
注释:
在您的情况下,您的数据框架应该没有重复的行,否则,应变表不仅包含0和1。计算应急表实际上是过度杀伤表。算法上更简单的方法(尽管使用更多的代码行)是:
Expanding comment to an answer.
This is known as a contingency table, and can be computed in several ways, without using fancy packages.
Such table is a matrix. If you want a data frame, coerce them using:
Remark:
In your case, your data frame should have no duplicated rows, otherwise a contingency table won't just contain 0 and 1. In this sense, computing a contingency table actually overkills. An algorithmically simpler way (although with more lines of code) is:
您可以通过
表
df
by或
You can use
table
overdf
either byor