0

I want to repeat heach column into a new row as the next example:

Date<- c(seq(as.Date("2000/1/1"), by = "month", length.out = 3))
A<- c(seq(2,4,length.out=3))
B<- c(seq(20,40,length.out=3))

df <- (data.frame(Date,A,B))
df
        Date A  B
1 2000-01-01 2 20
2 2000-02-01 3 30
3 2000-03-01 4 40

I would like to have this:

# Final dataframe
        Date  Site  Value
1 2000-01-01     A      2
2 2000-02-01     A      3
3 2000-03-01     A      4
4 2000-01-01     B     20
5 2000-02-01     B     30
6 2000-03-01     B     40

is there a function to make this?

francisco corvalan
  • 300
  • 1
  • 4
  • 10
  • As suggested, try something like `pivot_longer(df, cols = c(A, B))` from `tidyr` – Ben Nov 24 '21 at 01:31

1 Answers1

1

You may use reshape2::melt

library(dplyr)
library(reshape2)
library(stringr)

df %>%
  melt %>%
  mutate(Date = str_extract(variable, "[0-9]")) %>%
  select(-variable) %>%
  arrange(Site)

  Site value Date
1    A    10    1
2    A    30    2
3    B    20    1
4    B    40    2
Park
  • 14,771
  • 6
  • 10
  • 29
  • 1
    You should note where `str_extract` comes from. Why are you extracting a single character out of the date? That loses what's probably important information – camille Nov 24 '21 at 01:22
  • @camille Thank you for reminding me. I didn't notice about stringr :D – Park Nov 24 '21 at 01:26