简体   繁体   中英

include columnheader as another column value for each observation in R

I'm looking for a way to add the column header (date) next to each observation.

take df :

structure(list(dates = c("wt", "id", "", ""), X6.1.2018 = c("dd", 
"a", "b", "c"), X6.2.2018 = c("qq", "d", "e", ""), X6.2.2018.1 = c("dd", 
"z", "y", "")), class = "data.frame", row.names = c(NA, -4L))

where df looks like:

dates   6/1/2018    6/2/2018    6/2/2018
wt       dd             qq        dd
id        a              d        z
          b              e        y
          c 

I'd like to end with df_final :

id  date
a   6/1/2018
b   6/1/2018
c   6/1/2018
d   6/2/2018
e   6/2/2018
z   6/2/2018
y   6/2/2018

Any ideas are helpful - thanks

With tidyverse :

library(tidyverse)

df %>%
  filter(dates != 'wt') %>%
  select(-dates) %>%
  gather(date, id) %>%
  filter(id != '') %>%
  mutate(date = as.Date(date, format = "X%m.%d.%Y"))

Output:

        date id
1 2018-06-01  a
2 2018-06-01  b
3 2018-06-01  c
4 2018-06-02  d
5 2018-06-02  e
6 2018-06-02  z
7 2018-06-02  y

or with data.table::melt :

library(data.table)

dt = setDT(df)[dates != 'wt', !'dates']
melt(dt, measure.vars = 1:3, variable.name = "date", 
     value.name = "id")[id != '', .(id, date = as.Date(date, format = "X%m.%d.%Y"))]

Output:

   id       date
1:  a 2018-06-01
2:  b 2018-06-01
3:  c 2018-06-01
4:  d 2018-06-02
5:  e 2018-06-02
6:  z 2018-06-02
7:  y 2018-06-02

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM