我有一个看起来像这样的表:
我需要它看起来像这样,net =毛重:
我该怎么做?
我首先将数据融化,然后作为列进行转换,然后为净读数创建新列。
df_m <- melt(df, id = 1:3)
df_c <- cast(df_m, ... ~ variable + type)
df_c$wr_net <- df_c$wr_gross - df_c$wr_tare
df_c$wc_net <- df_c$wc_gross - df_c$wc_tare
df_c$tsa_net <- df_c$tsa_gross - df_c$tsa_tare
哪个给出了
但是现在我无法弄清楚如何融合这个表格以使数据框看起来像我需要的方式,其中'type'列的值为'gross'和'tare'和'net'。
有更简单的方法吗?我是用熔化/铸造吠叫错误的树吗?
您可以使用此功能重现我的数据的一小部分......
df <- structure(list(train = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "AC0485n", class = "factor"),
position = c(1L, 1L, 2L, 2L, 3L, 3L), type = structure(c(2L,
1L, 2L, 1L, 2L, 1L), .Label = c("gross", "tare"), class = "factor"),
wids_raw = c(24.85, 146.2, 26.16, 135, 24.7, 135.1), wids_corr = c(26.15,
145.43, 27.44, 134.43, 26, 134.52), tsa = c(24.1, 139.2,
25, 133.6, 24, 131.1)), .Names = c("train", "position", "type",
"wr", "wc", "tsa"), class = "data.frame", row.names = c(NA,
-6L))
答案 0 :(得分:4)
如果你真的想用重塑来做,我就是这样做的:
library(reshape2)
df_m <- melt(df, id = 1:3)
df_c <- dcast(df_m, ... ~ type)
df_c$net <- df_c$gross - df_c$tare
df_m2 <- melt(df_c, 1:3)
names(df_m2)[4] <- "type"
dcast(df_m2, ... ~ variable)
答案 1 :(得分:3)
我认为你需要的只是使用ddply:
ddply(df,.(position),.fun=function(x){
newrow <- x[1,]
newrow$type <- "net"
newrow[4:6] <- x[x$type=="gross",4:6] - x[x$type=="tare",4:6]
return(rbind(x,newrow))
})
返回,
train position type wr wc tsa
1 AC0485n 1 tare 24.85 26.15 24.1
2 AC0485n 1 gross 146.20 145.43 139.2
3 AC0485n 1 net 121.35 119.28 115.1
4 AC0485n 2 tare 26.16 27.44 25.0
5 AC0485n 2 gross 135.00 134.43 133.6
6 AC0485n 2 net 108.84 106.99 108.6
7 AC0485n 3 tare 24.70 26.00 24.0
8 AC0485n 3 gross 135.10 134.52 131.1
9 AC0485n 3 net 110.40 108.52 107.1
编辑: 我认为如果你真的想使用熔化/铸造,这是有效的:
dd <- melt.data.frame(df_c,id.vars=1:2)
dd$type <- factor(do.call("rbind",strsplit(as.character(dd$variable),"_"))[,2])
dd$variable <- factor(do.call("rbind",strsplit(as.character(dd$variable),"_"))[,1])