转置数据框

问题描述 投票:2回答:1

有我的情况

  > 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

r dplyr
1个回答
1
投票

gathering为'long'格式后,一个选项是将'happy'中与'key'列中的“color”对应的值替换为否定值,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)
© www.soinside.com 2019 - 2024. All rights reserved.