r - 使用 R 中不同列的值透视数据
问题描述
抱歉,如果我重复发布,但我尝试了我在 stackoverflow 中看到的不同的东西并且不能完全解决问题或理解我为什么会遇到它。
所以我有一个这样的数据集:
council_name <- c("Barking and Dagenham","Barking and Dagenham","Barking and Dagenham","Barking and Dagenham","Barking and Dagenham","Barking and Dagenham","Barking and Dagenham","Barking and Dagenham","Barnet","Barnet")
period <- c("1st 2006", "1st 2006", "1st 2006", "1st 2006", "2nd 2006", "2nd 2006", "2nd 2006", "2nd 2006", "1st 2006", "1st 2006")
category <- c ("glass", "fridges", "paper", "glass", "glass", "fridges", "paper", "glass", "glass", "fridges")
data <- c(333, 222, 100, 98, 450, 540, 33, 450, 560, 120)
category2 <- c ("collected", "collected", "collected", "no donors", "collected", "collected", "collected", "no donors", "collected", "collected")
df <- data.frame (council_name, period, category, category2, data)
我想要的是这样的:
council_name <- c("Barking and Dagenham","Barking and Dagenham","Barnet")
period <- c("1st 2006", "2nd 2006", "1st 2006")
glass <- c(333, 450, 560)
fridges <- c(222,540,120)
paper <- c(100, 33, NA)
no.donors <- c(98, 450, NA)
df.desired <- data.frame (council_name, period, glass, fridges, paper, no.donors)
我一直在尝试使用数据透视函数做多种事情,但事实上我需要从 category1 和 category2 中提取列名,但是用 df 中同一列的值填充单元格,这给我带来了各种各样的问题。
非常感谢您的帮助!
解决方案
这是一个tidyverse
解决方案,pivot_wider
用于将数据转换为宽格式,然后用于rename
更改列名。
library(tidyverse)
df %>%
# Pivot from long to wide format using the first two columns as id cols and using both category and category2 columns to get the new column names
pivot_wider(id_cols = c(council_name,period),
names_from = c(category, category2),
values_from = data) %>%
# Rename the columns
rename("glass" = "glass_collected",
"fridges" = "fridges_collected",
"paper" = "paper_collected",
"no.donors" = "glass_no donors")
# A tibble: 3 x 6
# council_name period glass fridges paper no.donors
# <fct> <fct> <dbl> <dbl> <dbl> <dbl>
# 1 Barking and Dagenham 1st 2006 333 222 100 98
# 2 Barking and Dagenham 2nd 2006 450 540 33 450
# 3 Barnet 1st 2006 560 120 NA NA
推荐阅读
- javascript - iframe 在 express js 中无法正常工作
- flutter - 颤振字符串空间在电子邮件中显示 +
- 3d - 定义多边形的绘制顺序
- python - Python - 使用for循环从列的子集中获取平均值/总和
- python - 通过python脚本测量每秒的clickhouse查询
- python - 使用 python 插入时的 mycursor.execute 问题
- delphi-5 - Delphi 5 - 舍入到小数点后 4 位异常
- javascript - 如何从 GeoJSON 对象中获取特定值
- python - 使用 connexion 和 swagger 制作的速率限制 REST API
- amazon-cloudformation - 如何更改导入资源的 DeletionPolicy 以便后续导入工作?