如何重塑数据框并将循环列转置为数据框行? [英] How to reshape dataframe and transpose recurring columns to dataframe rows?
问题描述
我有一个包含重复列的数据框(间隔为5)。
I have a dataframe that has recurring columns (the interval is 5).
这就是它的样子:我有5种类型的列,它们随时间重复一次。重复出现的列的名称都有一个后缀,也可以删除/重命名,以便它们都可以匹配。
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.
我想做的是转置这些重复出现的列排成一行,所以最后我只有5列(日期,PX_LAST,PX_HIGH,PX_VOLUME,名称)。然后,我将能够按日期,名称等对数据框进行分组,并执行许多其他操作。
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.
预先感谢!
推荐答案
一个选择是将数据拆分
到列表
基于列名,然后一起 rbind
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
或另一种选择是遍历唯一
名称,对数据进行子集,取消列表
,并转换为 data.frame
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
data
dft <- data.frame("Date" = 1:2, "Age" = c(21,15), "Date" = 1:2, "Age" = c(32,12))
这篇关于如何重塑数据框并将循环列转置为数据框行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!