【问题标题】:transform data frame using tidyr [duplicate]使用 tidyr 转换数据框
【发布时间】:2020-08-17 12:28:08
【问题描述】:

我有这个:

library(tidyr)

haves <- data.frame(
        model1_prediction = c(1, 2)
        , model2_prediction = c(3, 4)
        , model3_prediction = c(5, 6)
        , actuals = c(99.1, 99.2)
      )

model1_prediction model2_prediction model3_prediction actuals                 
1                 3                 5    99.1
2                 4                 6    99.2

我想得到这个:

wants <- data.frame(
        long = c(1, 2, 3, 4, 5, 6)
        , actuals = c(99.1, 99.2, 99.1, 99.2, 99.1, 99.2)
     )

wants

long actuals
1    99.1
2    99.2
3    99.1
4    99.2
5    99.1
6    99.2

我长期受伤的工作尝试如下,但想知道是否有更好的方法?谢谢。

t1 <- haves %>%
    select(
        model1_prediction
        , model2_prediction
        , model3_prediction
    ) %>%
    mutate(
        id = row_number()
    ) %>%
    gather(
       key, long, -id
    )
t1
t2 <- haves %>%
    select(
        actuals
    ) %>%
    mutate(
        id = row_number()
    ) %>%
    gather(
       key, actuals, - id
    )
t2
my_longwounded_wants <- t1 %>%
    inner_join(t2, by = c("id" = "id")) %>%
    select(
        long
        , actuals
    )
my_longwounded_wants

【问题讨论】:

    标签: r tidyr


    【解决方案1】:

    试试这个:

    library(tidyr)
    
    haves %>% pivot_longer(cols = -actuals) %>% arrange(value) %>% select(value,actuals)
    

    输出:

      value actuals
    1     1    99.1
    2     2    99.2
    3     3    99.1
    4     4    99.2
    5     5    99.1
    6     6    99.2
    

    【讨论】:

    • 我是否认为排列是多余的?
    • @cs0815 这取决于您希望最终输出的方式。当然你可以避免它:)
    【解决方案2】:

    您可以在pivot_longer() 中设置names_to = NULL 来删除记录原始列名的列。这样可以节省您使用select() 的时间,使代码更简洁。

    library(tidyr)
    library(dplyr)
    
    haves %>%
      pivot_longer(-actuals, names_to = NULL) %>%
      arrange(value)
    
    # # A tibble: 6 x 2
    #   actuals value
    #     <dbl> <dbl>
    # 1    99.1     1
    # 2    99.2     2
    # 3    99.1     3
    # 4    99.2     4
    # 5    99.1     5
    # 6    99.2     6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 2021-01-14
      • 2019-07-23
      • 2022-11-21
      • 2018-01-16
      • 2016-01-22
      相关资源
      最近更新 更多