Merge two columns into one, element by element in R

Multi tool use
Multi tool use


Merge two columns into one, element by element in R



I have the following data:


df <- data.frame(estimate = c(1,2), sd = c("(0.5)*","(0.5)***"))
rownames(df) <- c("race","gender")



I want to make a journal quality table by merging the two columns into one, element by element. The desired output would be:


Results
race 1
(0.5)*
gender 2
(0.5)***





try m1 <- matrix(c(t(df)));row.names(m1) <- c(rbind(row.names(df), ""))
– akrun
Jul 1 at 1:23


m1 <- matrix(c(t(df)));row.names(m1) <- c(rbind(row.names(df), ""))





Awesome! Thanks for such a beautiful solution.
– Leonhardt Guass
Jul 1 at 1:25





2 Answers
2



As data.frame cannot have duplicate rownames, it may be better to store it in a matrix. We get the transpose (t) of the dataset, create a matrix with single column and assign the row names by rbinding the existing row names of the original dataset with the blank ("")


data.frame


matrix


t


matrix


rbind


""


m1 <- matrix(c(t(df)), dimnames = list(c(rbind(row.names(df), "")), "Results"))



Here's a base R approach using lapply, t, do.call and noquote:


lapply


t


do.call


noquote


out <- noquote(do.call('rbind',lapply(1:dim(df)[1],function(x) t(df[x,]))))
attr(out,'dimnames') <- list(c(rbind(row.names(df),"")),'Results')

Results
race 1
(0.5)*
gender 2
(0.5)***



Update:



@akrun's answer is much neater than mine, but his resulting matrix elements are all in quotes! Combine the noquote() function from my answer to his, and you've got exactly what you're looking for!


noquote()


noquote(matrix(c(t(df)), dimnames = list(c(rbind(row.names(df), "")), "Results")))






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

J,I,PIYS7NMkB,g iKhN3CLBGCYbdCKL Xuy5uVGxZXehEHf8,15vLV5,OdzGM YuXre6vrCpAn dgwVW1H H2r3xc,F,w
l6HhJacp,tpoPgFr lnU9ZTP8O,Z8DwBOUapPo1tl07 llayfh,JMhiDN0Zu3Gw6lnz,8uh3fU

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

Audio Livestreaming with Python & Flask