Merge two columns by having alternating rows
Hi Biostars,
I have been trying to merge two columns into a single column in R but I think I am missing something.
My dataframe looks something like this:
> df
Gene_name Sequence
GAPDH ATTTCGGGA
ENAM GGGCTTACG
KRAS AAATGCTTTC
I would like to create a single-column dataframe that will show the gene and the sequence right underneath like so:
> Merge
GAPDH
ATTTCGGGA
ENAM
GGGCTTACG
KRAS
AAATGCTTTC
Ive tried this: test<-cat(df$Gene_name,"\n",df$Sequence)
Doesnt seem to work..
Any ideas?
Many thanks, Gina
• 4,832 views
•
link
1 answer
Your example data
df <- structure(list(Gene_name = c("GAPDH", "ENAM", "KRAS"), Sequence = c("ATTTCGGGA",
"GGGCTTACG", "AAATGCTTTC")), class = "data.frame", row.names = c(NA,
-3L))
You can pivot the data to long format to accomplish this. I use the tidyverse here.
library("dplyr")
library("tidyr")
long <- df %>%
pivot_longer(everything()) %>%
select(!name)
> long
# A tibble: 6 x 1
value
<chr>
1 GAPDH
2 ATTTCGGGA
3 ENAM
4 GGGCTTACG
5 KRAS
6 AAATGCTTTC
• 0 views
•
link
Log in to answer this question.
Do you want an actual new line or have all in the same column?
Something like
df %>% transmute(col1 = paste0(col1, ",", col2)) %>% separate_rows(col1, sep = ",")? (The packages you'll need for this aremargittr,dplyr, andtidyr.)I think you can use
sedor something similar to convert spaces/tabs to newlines.Converting df to parsable formats are better. Please try below:
This way, you can further manipulate fasta in R.