将table()输出转换为矩阵(或数据框)

huangapple go评论62阅读模式
英文:

Converting a table()-output to a matrix (or dataframe)

问题

使用以下代码将结果转换为与上面输出相同的数据框或矩阵:

result <- table(df$Factor1, df$Factor2)
result_df <- as.data.frame.matrix(result)

希望这有帮助!

英文:

With

df &lt;- data.frame(Factor1 = factor(c(rep (&quot;A&quot;, 2), rep (&quot;B&quot;, 2), rep(&quot;C&quot;, 2))),
                 Factor2 = factor(LETTERS[12:7]))

table(df$Factor1, df$Factor2)

how to convert the result:

    G H I J K L
  A 0 0 0 0 1 1
  B 0 0 1 1 0 0
  C 1 1 0 0 0 0

into a dataframe or matrix that looks exactly like the output above?

Thanks!

答案1

得分: 2

以下是翻译好的内容:

df <- data.frame(Factor1 = factor(c(rep("A", 2), rep("B", 2), rep("C", 2))),
                 Factor2 = factor(LETTERS[12:7]))

result <- table(df$Factor1, df$Factor2)
result_df <- as.data.frame.matrix(result)

print(result_df)

result:

  G H I J K L
A 0 0 0 0 1 1
B 0 0 1 1 0 0
C 1 1 0 0 0 0
英文:
df &lt;- data.frame(Factor1 = factor(c(rep(&quot;A&quot;, 2), rep(&quot;B&quot;, 2), rep(&quot;C&quot;, 2))),
                 Factor2 = factor(LETTERS[12:7]))

result &lt;- table(df$Factor1, df$Factor2)
result_df &lt;- as.data.frame.matrix(result)

print(result_df)

result:

  G H I J K L
A 0 0 0 0 1 1
B 0 0 1 1 0 0
C 1 1 0 0 0 0

huangapple
  • 本文由 发表于 2023年5月25日 20:46:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定