使用Tidyr转换数据帧

问题描述

我有这个:

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

解决方法

尝试一下:

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
,

您可以在names_to = NULL中设置pivot_longer(),以删除记录原始列名的列。这样可以节省您使用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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...