r - 根据其他数据集中的其他值创建变量
问题描述
我想创建变量来计算每个市镇的每个政党的席位数量,所以我得到以下信息:
df <- data.frame(
stringsAsFactors = FALSE,
municipality= c("Aa en Hunze","Aa en Hunze",
"Aa en Hunze","Aalburg","Aalburg","Aalsmeer",
"Aalsmeer","Aalten","Aalten","Achtkarspelen","Achtkarspelen",
"Alblasserdam","Alblasserdam","Alblasserdam",
"Albrandswaard","Albrandswaard","Almelo","Almelo","Almelo",
"Almelo","Almere","Almere","Almere","Almere",
"Alphen-Chaam","Alphen-Chaam","Ameland","Ameland","Amersfoort",
"Amersfoort","Amersfoort","Amersfoort","Amstelveen",
"Amstelveen","Amstelveen","Amstelveen","Amsterdam",
"Amsterdam","Amsterdam","Amsterdam"),
party = c("VVD","CDA",
"Democraten 66 (D66)","CDA","VVD","CDA","VVD","CDA","VVD","CDA",
"VVD","CDA","Democraten 66 (D66)","VVD","VVD","CDA",
"CDA","Democraten 66 (D66)","SP (Socialistische Partij)",
"VVD","Democraten 66 (D66)","VVD",
"SP (Socialistische Partij)","CDA","CDA","VVD","CDA","VVD",
"Democraten 66 (D66)","VVD","CDA","SP (Socialistische Partij)",
"VVD","Democraten 66 (D66)","CDA",
"SP (Socialistische Partij)","Democraten 66 (D66)",
"SP (Socialistische Partij)","VVD","CDA"),
seats= c(3L,2L,2L,3L,1L,6L,6L,7L,
2L,5L,1L,3L,2L,2L,6L,2L,6L,4L,4L,3L,6L,5L,
4L,2L,4L,1L,3L,1L,9L,5L,4L,4L,9L,8L,3L,3L,
14L,6L,6L,1L)
)
例如,我想创建一个名为 VVD 的变量,然后创建每个城市的所有席位。
由reprex 包于 2020-06-16 创建(v0.3.0)
我不知道如何在 r 中编码,有人可以帮助我吗?
解决方案
您可以使用xtabs
来计算每个市镇和政党的席位。
xtabs(seats ~ municipality + party, df)
# party
#municipality CDA Democraten 66 (D66) SP (Socialistische Partij) VVD
# Aa en Hunze 2 2 0 3
# Aalburg 3 0 0 1
# Aalsmeer 6 0 0 6
# Aalten 7 0 0 2
# Achtkarspelen 5 0 0 1
# Alblasserdam 3 2 0 2
# Albrandswaard 2 0 0 6
# Almelo 6 4 4 3
# Almere 2 6 4 5
# Alphen-Chaam 4 0 0 1
# Ameland 3 0 0 1
# Amersfoort 4 9 4 5
# Amstelveen 3 8 3 9
# Amsterdam 1 14 6 6
推荐阅读
- performance - 在 Unity 中使用 SetAsFirstSibling 还是 SetAsLastSibling 更好?
- javascript - Angular http 流双重请求 [GET,HEAD]
- git - 使用 Dockerfile RUN 克隆 bitbucket 存储库
- python - Python 2.7:如何弥补缺少的 pool.starmap?
- c# - 如何在asp.net中使用if else语句集成多个sql查询
- macos - Linux 和 macOS 之间的 LC_COLLATE(排序顺序)差异
- qt - QT QPrinter 打印部分页面
- android - Android Fragment 之间的通信
- python - 使用 AUTH_USER_MODEL 覆盖 django 用户
- r - 在 InsertUI 函数中使用 Popover (shinybs)