转置数据框

时间:2018-10-24 18:25:27

标签: r dplyr

遇到我有的情况

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

1 个答案:

答案 0 :(得分:1)

gather设为“长”格式后,一种选择是替换与“键”列中“颜色”相对应的“快乐”中的值作为负值,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)