Pivot Wider in R

…衆ロ難τιáo~ 提交于 2021-02-16 15:28:49

问题


I have a dataframe like this

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

I want to pivot it to look like this

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

I've tried this:

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?


回答1:


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   

data

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))


来源:https://stackoverflow.com/questions/63402239/pivot-wider-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!