我有一个看起来像这样的数据框:
a <- c("Lilo","Chops","Henmans")
a <- cbind(a,c(0.1,0.5,0.25),c(0.2,0.3,0.65),c(0.7,0.2,0.1))
colnames(a) <- c("market","Product A","Product B","Product C")
并想融化它:
b <- melt(a, varnames = c("market"))
这给出了以下内容:
> b
market NA value
1 1 market Lilo
2 2 market Chops
3 3 market Henmans
4 1 Product A 0.1
5 2 Product A 0.5
6 3 Product A 0.25
7 1 Product B 0.2
8 2 Product B 0.3
9 3 Product B 0.65
10 1 Product C 0.7
11 2 Product C 0.2
12 3 Product C 0.1
>
但是,我要寻找的是
> b
market NA value
4 Lilo Product A 0.1
5 Chops Product A 0.5
6 Henmans Product A 0.25
7 Lilo Product B 0.2
8 Chops Product B 0.3
9 Henmans Product B 0.65
10 Lilo Product C 0.7
11 Chops Product C 0.2
12 Henmans Product C 0.1
我如何使用熔体实现这一目标?
尝试使用rownames
而不是单独的列market
。这样,您可以得到一个数值矩阵,并且可以使用melt
如下所示的非常简单的方法:
a <- cbind(c(0.1,0.5,0.25),c(0.2,0.3,0.65),c(0.7,0.2,0.1))
rownames(a) <- c("Lilo","Chops","Henmans")
colnames(a) <- c("Product A","Product B","Product C")
一个现在看起来是这样的:
Product A Product B Product C
Lilo 0.10 0.20 0.7
Chops 0.50 0.30 0.2
Henmans 0.25 0.65 0.1
您可以使用访问“市场” rownames(a)
。
融化现在的工作方式如下(melt.array
用于执行重塑):
melt(a)
Var1 Var2 value
1 Lilo Product A 0.10
2 Chops Product A 0.50
3 Henmans Product A 0.25
4 Lilo Product B 0.20
5 Chops Product B 0.30
6 Henmans Product B 0.65
7 Lilo Product C 0.70
8 Chops Product C 0.20
9 Henmans Product C 0.10
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句