How to reshape a wider data.frame to longer data.frame in R? [duplicate]

半世苍凉 提交于 2021-02-10 22:15:51

问题


I was playing with pivot_longer and pivot_wider but probably am missing something. I have a data.frame like D_Wider and would like to convert it to something like D_longer. any way forward?

library(tidyverse)
D_Wider <- data.frame(A = 15, S = 10, D = 25, Z = 16)

Desired Output

D_Longer <- data.frame(Stations = c("A","S","D","Z"), Value = c(15,10,25,16))

回答1:


Easiest would be stack from base R

stack(D_Wider)[2:1]

Or using pivot_longer

library(tidyr)
pivot_longer(D_Wider, cols = everything(), 
     names_to = 'Stations', values_to = 'Value')


来源:https://stackoverflow.com/questions/63024920/how-to-reshape-a-wider-data-frame-to-longer-data-frame-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!