我正在尝试转换包含宽数据和长数据的组合的数据集。当前看起来像这样:
(注意:两侧还有很多其他变量,这只是我需要更改的部分)
当前,WTP1和2与同一参与者(买方)相关联,位于同一行中。我需要的是WTP的一列,因此每个买方都有两行,除了WTP值相同。像这样:
WTP
15
5
我几乎已经使用unite函数达成了一个解决方案,但问题是这两个值在同一单元格中,而不是在它们自己的行中:
library(dplyr)
long_Data <- unite(mydata.sub1,WTP,player.WTP1:player.WTP2, sep = "_", remove= TRUE)
我敢肯定有一个简单的解决方案,但是我是一个初学者!任何建议欢迎。 TIA
答案 0 :(得分:1)
这是您要找的吗?
df1 <- data.frame(
player.WTA = c(NA,20,10,NA,10,5,NA),
player.WTP1 = c(15,NA,NA,15,NA,NA,15),
player.WTP2 = c(5,NA,NA,5,NA,NA,5)
)
require(reshape2)
melt(df1, id.var="player.WTA", value.name="WTP")
player.WTA variable WTP
1 NA player.WTP1 15
2 20 player.WTP1 NA
3 10 player.WTP1 NA
4 NA player.WTP1 15
5 10 player.WTP1 NA
6 5 player.WTP1 NA
7 NA player.WTP1 15
8 NA player.WTP2 5
9 20 player.WTP2 NA
10 10 player.WTP2 NA
11 NA player.WTP2 5
12 10 player.WTP2 NA
13 5 player.WTP2 NA
14 NA player.WTP2 5
如果您只想查看非NA值:
require(dplyr)
melt(df1, id.var="player.WTA", value.name="WTP") %>% filter(WTP != 'NA')
player.WTA variable WTP
1 NA player.WTP1 15
2 NA player.WTP1 15
3 NA player.WTP1 15
4 NA player.WTP2 5
5 NA player.WTP2 5
6 NA player.WTP2 5
答案 1 :(得分:1)
只需查看您的前三行并做一些假设(添加id和捐赠列)...
var allWheels = new List<char[]> { w1, w2, w3, w4, w5 };
var totalNumCombos = allWheels.Select(w => w.Length).Aggregate(1, (a, n) => a * n);
var numWheels = allWheels.Count;
var numWheelsm1 = numWheels-1;
var wheelbase = w1.Length; // use an array for different sized wheels
// allWheels.Select(w => w.Length).ToArray();
var allCombos = new List<string>();
var sbCombo = new StringBuilder(new String(allWheels.ToArray().Reverse().Select(w => w[0]).ToArray()));
for (int aComboInDecimal = 0; aComboInDecimal < totalNumCombos; ++aComboInDecimal) {
var num = aComboInDecimal;
for (var digit = 0; digit < numWheels && num > 0; ++digit) {
var digitVal = num % wheelbase; // wheelbase[digit]
num = num / wheelbase; // wheelbase[digit]
sbCombo[numWheelsm1-digit] = allWheels[digit][digitVal];
}
allCombos.Add(sbCombo.ToString());
}
我建议以一致的方式为买卖双方设置格式:
DF = data.frame(
id = 1:3,
endowment = c(0L, 1L, 1L),
WTA = c(NA, 20, 10),
WTP.1 = c(15, NA, NA),
WTP.2 = c(5, NA, NA)
)
id endowment WTA WTP.1 WTP.2
1 1 0 NA 15 5
2 2 1 20 NA NA
3 3 1 10 NA NA
我用来从DF到达那里的R代码...
prefs = data.frame(id = rep(1:3, c(2,1,1)), quantity = c(1L,2L,-1L,-1L), valuation = c(15,20,-20,-10))
id quantity valuation
1 1 1 15
2 1 2 20
3 2 -1 -20
4 3 -1 -10
players = data.frame(id = 1:3, endowment = c(0L, 1L, 1L))
id endowment
1 1 0
2 2 1
3 3 1