如何解决使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。