gpt4 book ai didi

r - 在 R 中,使用 melt 和 cast reshape "mixed"数据框

转载 作者:行者123 更新时间:2023-12-02 01:28:06 28 4
gpt4 key购买 nike

我想绘制两种类型的值(dupl 和 orig)。是否可以轻松 reshape 以下数据框

record=c("r1","r1","r2","r3","r3")
v1=rep(0,5)
v2=c(0,0,1,0,0)
v3=c(1,1,0,1,1)
type=c("orig","dupl","orig","orig","dupl")

df<-data.frame(record, v1, v2, v3, type)
df
record v1 v2 v3 type
1 r1 0 0 1 orig
2 r1 0 0 1 dupl
3 r2 0 1 0 orig
4 r3 0 0 1 orig
5 r3 0 0 1 dupl

看起来像这样?

record  v1.orig v2.orig v3.orig v1.dupl v2.dupl v3.dupl
r1 0 0 1 0 0 1
r2 0 1 0
r3 0 0 0 0 0 0

关键是我可以绘制 vX.orig 与 vX.dupl 的对比图。或者有更好的方法吗?我正在查看 dcast() 但似乎无法得到我想要的,可能是因为我的数据只是部分熔化(沿着类型?)。

编辑:这是我尝试过的:

df1<-melt(df,id="record")
dcast(df1,record~value, margins=TRUE)

最佳答案

你可以这样做:

library(reshape2)
melted <- melt(df, id.vars= c("record", "type"))
dcast(melted, record ~ variable + type)

record v1_dupl v1_orig v2_dupl v2_orig v3_dupl v3_orig
1 r1 0 0 0 0 1 1
2 r2 NA 0 NA 1 NA 0
3 r3 0 0 0 0 1 1

或者我原来的回答:

library(tidyverse)
df %>% gather(vx, num, -record, -type) %>%
unite(type, vx, type) %>%
spread(type, num)

关于r - 在 R 中,使用 melt 和 cast reshape "mixed"数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42078558/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com