How to reshape dataframe and transpose recurring columns to dataframe rows?

六眼飞鱼酱① 提交于 2019-12-20 05:12:07

问题


I have a dataframe that has recurring columns (the interval is 5).

my dataframe at the moment

So this is how it looks: I have 5 type of columns and they repeat time over time. The recurring columns have a suffix in their name, this can be removed/renamed as well, so that they would all match.

What I would like to do is to transpose these recurring columns to rows, so that I would have only 5 columns in the end (Dates, PX_LAST, PX_HIGH, PX_VOLUME, Name). Then I would be able to group the dataframe by Dates, Name etc and do many other things.

I tried some manipulations with pipe operator %>%, but it didn't really work at the moment. Since I don't have any ideas left, I thought, that maybe you could help me out.

Thanks in advance!


回答1:


One option would be to split the data into a list of data.frame based on the column names and then rbind them together

nm1 <-  sub("\\.\\d+", "", names(dft))
i1 <- ave(seq_along(dft), nm1, FUN = seq_along)
out <- do.call(rbind, lapply(split.default(dft, i1), 
      function(x) setNames(x, sub("\\.\\d+", "", names(x)))))
row.names(out) <- NULL
out
#  Date Age
#1    1  21
#2    2  15
#3    1  32
#4    2  12

Or another option is to loop through the unique names, subset the data, unlist, and convert to data.frame

un1 <- unique(nm1)
setNames(data.frame(lapply(un1, 
       function(x) unlist(dft[grep(x, names(dft))]))), un1)

data

dft <- data.frame("Date" = 1:2, "Age" = c(21,15), "Date" = 1:2, "Age" = c(32,12))


来源:https://stackoverflow.com/questions/55759687/how-to-reshape-dataframe-and-transpose-recurring-columns-to-dataframe-rows

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