【问题标题】:How to partially transpose a dataframe in R? (specific column to row)如何在 R 中部分转置数据框? (特定列到行)
【发布时间】:2021-07-09 11:21:41
【问题描述】:

我想将特定列更改为每个单元格的值基于另一列的行。

我的数据框如下所示:

Race State Region Decile Freq
African a A 1 3
Caucasian a A 1 7
Asian a A 1 9
Mulatto a A 1 5
African b B 1 12
Caucasian b B 1 2
Asian b B 1 8
Mulatto b B 1 5

我想将 Race 列更改为一行(其中 Freq 确定每个单元格的值),所以我得到以下输出:

State Region Decile African Caucasian Asian Mulatto
a A 1 3 7 9 5
b B 1 12 2 8 5

这里的最终目的是计算每个州、地区和十分位的每个种族的相对频率,但这是另一天

【问题讨论】:

标签: r dataframe reshape


【解决方案1】:

tidyr::pivot_wider:

library(tidyr)

data %>% pivot_wider(names_from = 'Race', values_from = Freq)
# A tibble: 2 x 7
  State Region Decile African Caucasian Asian Mulatto
  <chr> <chr>   <int>   <int>     <int> <int>   <int>
1 a     A           1       3         7     9       5
2 b     B           1      12         2     8       5

数据:

data <- read.table(text=
'Race   State   Region  Decile  Freq
African     a   A   1   3
Caucasian   a   A   1   7
Asian   a   A   1   9
Mulatto     a   A   1   5
African     b   B   1   12
Caucasian   b   B   1   2
Asian   b   B   1   8
Mulatto     b   B   1   5', header=T)

【讨论】:

  • 很高兴我能帮上忙!请考虑accepting the answer,以便其他人知道它有效并且也可以从中受益。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 2013-09-05
  • 2022-12-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
相关资源
最近更新 更多