转换数据框

时间:2016-04-12 22:29:19

标签: r dataframe

我在R中有一个数据框,大约有7k行。

Customer ID  Test_Control DF    Purchase 
1112223333      test      ab     False  
2222223333      Control   ab     False
3332223333      Control   ab     True
4442223333      test      ab     False

关于数据:

  • 所有Customer_ID都是唯一的。
  • "购买"列为True或false
  • " Test_Control"列是" test"或"控制"
  • DF专栏总是" ab"

我需要将其转换为如下所示:

Test     Control
0        1
0        1
1        0 
0        1

关于转型:

  • 如果Test_control列是Test或Control
  • ,则应将其分为两列
  • 如果购买栏中有"错误"对于"测试"它应该是0和"控制"柱
  • 如果“购买”列是“真实”,那么那么" 1"应该进入"测试"或"控制"柱。例如,如果" test_control"列是测试然后1将进入"测试"列。

基本上,我正在准备这个t.test()。

2 个答案:

答案 0 :(得分:1)

使用reshape2库,可以保持与原始数据的链接:

library(reshape2)
df <- data.frame(Customer.ID = c(1112223333, 2222223333, 3332223333, 4442223333),
                 Test_Control = c("test", "Control", "Control", "test"),
                 DF = rep("ab", 4),
                 Purchase = c(FALSE, FALSE, TRUE, FALSE))
#Add dummy column with the desire result    
df$result<-1
#cast the data frame
dcast(df, Customer.ID + Purchase + DF ~ Test_Control, fill=0)

答案 1 :(得分:0)

您可以使用ifelse。对于每个变量,它会检查Purchase是否为false,在这种情况下,它会指定值0.否则,它会检查Test_Control的值以确定是分配1还是0。

df <- data.frame(Customer.ID = c(1112223333, 2222223333, 3332223333, 4442223333),
                 Test_Control = c("test", "Control", "Control", "test"),
                 DF = rep("ab", 4),
                 Purchase = c(FALSE, FALSE, TRUE, FALSE))

df$Test <- ifelse(!df$Purchase, 0, ifelse(df$Test_Control=="test", 1, 0))
df$Control <- ifelse(!df$Purchase, 0, ifelse(df$Test_Control=="Control", 1, 0))