首页 > 解决方案 > 转置数据帧

问题描述

有我遇到的情况

  > sample_df <- data.frame(id = c(14129, 29102, 2191, 2192, 1912)
                        , color = c("blue", "red", "green", "purple", "blue")
                        , day = c("monday", "wednesday", "thursday", "monday", "tuesday")
                        , happy = c(1, 1, 1, 1, 1))

  > sample_df 
     id  color       day happy
  14129   blue    monday     1
  29102    red wednesday     1
   2191  green  thursday     1
   2192 purple    monday     1
   1912   blue   tuesday     1

希望能够创建一个将两列转置为具有以下内容的列:

> sample_df_2 <- data.frame(id = c(14129,14129, 29102,29102, 2191,2191, 2192,2192, 1912,1912)
                          , type = c("blue", "monday","red","wednesday","green","thursday","purple","monday","blue","tuesday")
                          , happy = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1))

> sample_df_2
      id      type happy
   14129      blue     0
   14129    monday     1
   29102       red     0
   29102 wednesday     1
    2191     green     0
    2191  thursday     1
    2192    purple     0
    2192    monday     1
    1912      blue     0
    1912   tuesday     1

关于最后一列的想法只是说,如果我们正在处理从原始color字段中提取的值,happy则为自动0,否则1

标签: rdplyr

解决方案


输入“long”格式后gather,一种选择是将“key”列中与“color”对应的“happy”中的值替换为否定值、select感兴趣的列以及arrange必要时

library(tidyverse)
gather(sample_df, key, type, color:day) %>%
    mutate(happy = case_when(key == "color" ~ as.numeric(!happy), TRUE ~ happy)) %>%
    select(-key) %>%
    arrange(id)

推荐阅读