R 从三个值创建交叉表

R 从三个值创建交叉表,r,crosstab,R,Crosstab,我有一个包含三个变量的数据框,我希望第一个变量是行名称,第二个变量是列名,第三个变量是与这两个参数相关联的值,在数据可能缺失的地方使用NA或空白。这在R中容易/可能做到吗 示例输入 structure(list( Player = c("1","1","2","2","3","3","4","4","5","5","6"), Type = structure(c(2L, 1L, 2L, 1L, 2L, 1L,2L, 1L, 2L, 1L, 1L), .Label = c("L

我有一个包含三个变量的数据框,我希望第一个变量是行名称,第二个变量是列名,第三个变量是与这两个参数相关联的值,在数据可能缺失的地方使用NA或空白。这在R中容易/可能做到吗

示例输入

structure(list(
  Player = c("1","1","2","2","3","3","4","4","5","5","6"),

  Type = structure(c(2L, 1L, 2L, 1L, 2L, 1L,2L, 1L, 2L, 1L, 1L),
     .Label = c("Long", "Short"), class = "factor"),
     Yards = c("23","41","50","29","11","41","48","12","35","27","25")),

  .Names = c("Player", "Type", "Yards"),

  row.names = c(NA, 11L),
  class = "data.frame")

使用您提供的示例数据:

df <- structure(list(Player = c("1", "1", "2", "2", "3", "3", "4", "4", "5",
 "5", "6"), Type = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L),
 .Label = c("Long", "Short"), class = "factor"), 
 Yards = c("23", "41", "50", "29", "11", "41", "48", "12", "35", "27", "25")), 
 .Names = c("Player", "Type", "Yards"), row.names = c(NA, 11L), 
 class = "data.frame")

   Player  Type Yards
1       1 Short    23
2       1  Long    41
3       2 Short    50
4       2  Long    29
5       3 Short    11
6       3  Long    41
7       4 Short    48
8       4  Long    12
9       5 Short    35
10      5  Long    27
11      6  Long    25
Player
列将是一个列,因此您需要做一些额外的工作,使其成为
data.frame的行名称

rownames(df.cast) <- df.cast$Player
df.cast$Player <- NULL

  Long Short
1   41    23
2   29    50
3   41    11
4   12    48
5   27    35
6   25  <NA>

rownames(df.cast)试试
table
xtab
。我已经试过了,但我刚刚能够计算出行值和列值同时出现的次数。我如何使用这些变量使第三个变量成为表中的值,而不是前两个变量的freq?您能给我们一个输入示例吗?看看给出一个例子的提示。看看它看起来会起作用!我回家后必须在我的真实数据上试用它。我也在看重塑包,但是熔化/铸造的东西有点超出了我的头脑。
rownames(df.cast) <- df.cast$Player
df.cast$Player <- NULL

  Long Short
1   41    23
2   29    50
3   41    11
4   12    48
5   27    35
6   25  <NA>