在 R 中枢轴更宽 [英] Pivot Wider in R

查看:19
本文介绍了在 R 中枢轴更宽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框

rest_id task_name quarter nc
123     labeling  1       TRUE
123     labeling  2       FALSE
123     labeling  3       FALSE
123     labeling  4       FALSE
123     cooking   1       TRUE
123     cooking   2       FALSE
123     cooking   3       TRUE
123     cooking   4       FALSE
123     cleaning  1       TRUE
123     cleaning  2       FALSE
123     cleaning  3       TRUE
123     cleaning  4       FALSE

我想把它旋转成这样

rest_id quarter labeling  cooking  cleaning
123     1       TRUE      TRUE     TRUE
123     2       FALSE     FALSE    FALSE
123     3       FALSE     TRUE     TRUE
123     4       FALSE     FALSE    FALSE

我已经试过了:

X <- pivot_wider(df,
                 names_from = task_name,
                 values_from = nc,
                 values_fill = list(nc=F))

但它没有给我我想要的输出..有人可以帮助我吗?

But it doesn't give me my intended output.. can someone help me?

推荐答案

我们不需要为宽格式创建列名向量.names_from 从数据集中的task_name"列中进行选择,并根据该列的唯一值创建宽列名称

We don't need to create a vector of column names for the wide format. The names_from is selecting from the 'task_name' column in the dataset and it creates the wide column name from the unique values of that column

library(dplyr)
library(tidyr)
df %>%
   pivot_wider(names_from = task_name, values_from = nc, 
           values_fill = list(nc = FALSE))
# A tibble: 4 x 5
#  rest_id quarter labeling cooking cleaning
#    <int>   <int> <lgl>    <lgl>   <lgl>   
#1     123       1 TRUE     TRUE    TRUE    
#2     123       2 FALSE    FALSE   FALSE   
#3     123       3 FALSE    TRUE    TRUE    
#4     123       4 FALSE    FALSE   FALSE   

数据

df <- structure(list(rest_id = c(123L, 123L, 123L, 123L, 123L, 123L, 
123L, 123L, 123L, 123L, 123L, 123L), task_name = c("labeling", 
"labeling", "labeling", "labeling", "cooking", "cooking", "cooking", 
"cooking", "cleaning", "cleaning", "cleaning", "cleaning"), quarter = c(1L, 
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), nc = c(TRUE, FALSE, 
FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE
)), class = "data.frame", row.names = c(NA, -12L))

这篇关于在 R 中枢轴更宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆