Transposing a dataframe maintaining the first column as heading

纵饮孤独 提交于 2019-11-27 20:08:23

问题


I have a big dataframe, but small example would be like this:

mydf <- data.frame(A = c(letters[1:10]), M1 = c(11:20), M2 = c(31:40), M3 = c(41:50))

I want to transpose the dataframe and maintain the column 1 (A) as column heading ( letter[1:10]) as variable names. The following are scratch trials of unsuccessful codes.

tmydf = data.frame(t(mydf))
names(tmydf) <- tmydf[1,]

Thanks;


回答1:


Here is one way

tmydf = setNames(data.frame(t(mydf[,-1])), mydf[,1])



回答2:


Something like this perhaps:

tmp <- as.data.frame(t(mydf[,-1]))
> colnames(tmp) <- mydf$A
> tmp
    a  b  c  d  e  f  g  h  i  j
M1 11 12 13 14 15 16 17 18 19 20
M2 31 32 33 34 35 36 37 38 39 40
M3 41 42 43 44 45 46 47 48 49 50



回答3:


Data.table variante from Ramnath with indicating in string the variable name wanted.

mydf <- data.table(A = c(letters[1:10]), M1 = c(11:20), M2 = c(31:40), M3 = c(41:50))
tmydf <- setNames(data.table(t(mydf[,-"A"])), mydf[["A"]])


来源:https://stackoverflow.com/questions/7970179/transposing-a-dataframe-maintaining-the-first-column-as-heading

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