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

假如想象 提交于 2019-12-02 04:18:54

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