Paolo Lorenzini
Paolo Lorenzini

Reputation: 725

Rearrange rows in data frame

I have a data frame in R which looks like this with two columns:

ID     phone_number
Mark     866458
Paul     986564
Jack     987543
Mary     523422

I would like to have this kind of output where I only have one single column

Mark
866458
Paul
986564
Jack
987543
Mary
523422

Anybody knows which R code could I use to obtain the output?


Data for reproducibility:

structure(list(ID = c("Mark", "Paul", "Jack", "Mary"), phone_number = c(866458, 
                                                                        986564, 987543, 523422)), row.names = c(NA, -4L), class = c("tbl_df", "data.frame"))

Upvotes: 3

Views: 362

Answers (4)

akrun
akrun

Reputation: 887971

We can also do

library(tidyverse)
pmap(df1, c) %>% 
       unlist %>% 
       tibble(new_col = .)

Upvotes: 2

DeduciveR
DeduciveR

Reputation: 1702

A longer method with an intermediate df, but may be of some value depending on your full dataset:

library(tidyverse)

df1 <- df %>% 
  rowid_to_column() %>%
  select(rowid, ID = phone_number) 

df2 <- df %>% 
  rowid_to_column() %>%
  select(rowid, ID) %>%
  rbind(df1) %>% 
  arrange(rowid) %>% 
  select(ID)

result:

  ID    
  <chr> 
1 Mark  
2 866458
3 Paul  
4 986564
5 Jack  
6 987543
7 Mary  
8 523422

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

We can transpose the dataframe and then create one vector of values

data.frame(new_col = c(t(df)))

#  new_col
#1    Mark
#2  866458
#3    Paul
#4  986564
#5    Jack
#6  987543
#7    Mary
#8  523422

Another base R option using mapply

data.frame(new_col = c(mapply(c, df$ID, df$phone_number)))

Upvotes: 7

tmfmnk
tmfmnk

Reputation: 40171

One possibility with tidyverse:

df %>%
 rowid_to_column() %>%
 gather(var, val, -rowid) %>%
 arrange(rowid) %>%
 select(val)

     val
1   Mark
2 866458
3   Paul
4 986564
5   Jack
6 987543
7   Mary
8 523422

Upvotes: 1

Related Questions