转置数据框 [英] Transposing a dataframe

查看:106
本文介绍了转置数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遇到一种情况

  > 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

希望能够创建一个将两列转置为类似列的列:

want to be able to create a column that transposes the two columns to have something like:

> 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

The idea about the last column is just to say, if we're dealing with a value pulled from the original color field then happy is automatically 0, otherwise 1

推荐答案

聚集为'long'格式后,一种选择是替换'happy'中的值对应于键列中颜色作为负值,选择感兴趣的列,排列

After gathering into 'long' format, one option is to replace the values in 'happy' that corresponds to "color" in 'key' column as the negated value, select the columns of interest and arrange if neccessary

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

这篇关于转置数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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