非结构化表向窄格式表转换?

时间:2018-11-15 03:06:12

标签: r dataframe

我需要将数据从示例1转到示例2。

# Example 1
data.frame(Player = c("Brad Abbey", "Wins", "Losses", "Neither", "Caleb Aekins", "Wins", "Losses", "Neither"),
                 No = c(1, NA, NA, NA))

#         Player No
# 1   Brad Abbey  1
# 2         Wins NA
# 3       Losses NA
# 4      Neither NA
# 5 Caleb Aekins  1
# 6         Wins NA
# 7       Losses NA
# 8      Neither NA


# Example 2
structure(list(Player = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L), .Label = c("Brad Abbey", "Caleb Aekins"), class = "factor"), 
Result = structure(c(3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L), class = "factor", 
.Label = c("Losses", 
"Neither", "Overall", "Wins"))), class = "data.frame", row.names = c(NA, 
-8L))

#         Player  Result
# 1   Brad Abbey Overall
# 2   Brad Abbey    Wins
# 3   Brad Abbey  Losses
# 4   Brad Abbey Neither
# 5 Caleb Aekins Overall
# 6 Caleb Aekins    Wins
# 7 Caleb Aekins  Losses
# 8 Caleb Aekins Neither

在将人员姓名复制到其下一行时,如何将“获胜”,“亏损”和“都不选择”移到其旁边的列?

1 个答案:

答案 0 :(得分:0)

您可以使用Players函数从列setdiff中提取玩家的姓名。然后创建一个输出表,每个玩家的名字重复4次,并循环Result个已知结果c("Overall","Wins", "Losses", "Neither")

请参见下面的代码

df <- data.frame(Player = c("Brad Abbey", "Wins", "Losses", "Neither", "Caleb Aekins", "Wins", "Losses", "Neither"),
                 No = c(1, NA, NA, NA))

outcome <- c("Overall","Wins", "Losses", "Neither")
name <- setdiff(unique(df$Player), outcome)
res <- data.frame(Player = unlist(lapply(name, rep, 4)), Result = outcome)
res

输出:

        Player  Result
1   Brad Abbey Overall
2   Brad Abbey    Wins
3   Brad Abbey  Losses
4   Brad Abbey Neither
5 Caleb Aekins Overall
6 Caleb Aekins    Wins
7 Caleb Aekins  Losses
8 Caleb Aekins Neither