R 将行值转置为列

标签 r statistics transpose

data %>% select(Year, Type) %>% table() 的输出给我:

Year  Type Freq
2001    A     5
2002    A     2
2003    A     9
...    ...  ...
2001    B    21   
2002    B    22
2003    B    19

我想要我的数据:

Year  A   B   C   D   E  
2001  5  21   ..  ..  ..
2002  2  22   ..  ..  .. 
2003  9  19   ..  ..  ..
...

我怎样才能实现这个目标?我找到的例子似乎与我的情况不符

最佳答案

使用reshape的基本R选项

reshape(
  df,
  direction = "wide",
  idvar = "Year",
  timevar = "Type"
)

给出

  Year Freq.A Freq.B
1 2001      5     21
2 2002      2     22
3 2003      9     19

data.table 选项

dcast(setDT(df), Year ~ Type)

给出

   Year A  B
1: 2001 5 21
2: 2002 2 22
3: 2003 9 19

dplyr 选项

df %>%
  pivot_wider(names_from = Type, values_from = Freq)

给出

# A tibble: 3 x 3
   Year     A     B
  <int> <int> <int>
1  2001     5    21
2  2002     2    22
3  2003     9    19

数据

> dput(df)
structure(list(Year = c(2001L, 2002L, 2003L, 2001L, 2002L, 2003L
), Type = c("A", "A", "A", "B", "B", "B"), Freq = c(5L, 2L, 9L,
21L, 22L, 19L)), class = "data.frame", row.names = c(NA, -6L))

关于R 将行值转置为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65778767/

相关文章:

javascript - 将 TD 数组转置为列 jQuery

python - 使用尽可能简单的索引在 python pandas 中转置一列

R将特定行和列乘以常数

statistics - 使用具有标准偏差的 BigQuery 检测异常值

arrays - Julia 中的等效 np.nanquantile 吗?

bash - 在 Bash 中计算百分位数

google-sheets - 使用数组公式在每一行上输入单行查询

r - 在我的主文档中包含几个 tex 格式的表格

r - 为什么这些内存功能不同?

r - 计算 %H 中的时间差 :%M:%S format in R