简体   繁体   English

包括 columnheader 作为 R 中每个观察的另一个列值

[英]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 :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:其中df看起来像:

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 :我想以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 :使用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 :或使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R - 对于列中的每个观察值,在另一列中找到最接近的观察值 - R - for each observation in a column, find the closest one in another column 复制观察 r 中另一列中每一行的列 - replicate observation of column for each row in another columns in r 从不同列中的另一个观察值中减去一个观察值,并将特定值添加到结果中以在 R 的第一列中创建一个新观察值 - Subtract an observation from another in different column and add a specific value to the result to create a new observation in the first column in R R-将每个字母因子的字母数字字符观测值拆分为列,并为每个观测值分配数值 - R - split alphanumeric char observations with column for each letter factor with value of numeric for each observation 如何使用R在每次观察中都不会出现的另一列中基于字符串的字符串grep? - How to grep a group based on string in another column that doesn't occur in each observation using R? 将重复观察的列变成R中每个观察的列 - Turn a column with repeating observations into a column for each observation in R R:按列组汇总数据-使用每个观察值对列进行变异 - R: Aggregating data by column group - mutate column with values for each observation R:按组,检查是否对于一个var的每个唯一值,至少有一个观察值,其中var的值等于另一个var的值 - R: By group, check if for each unique value of one var, there is at least one observation where the value of the var equals the value of another var 如何知道一列中每个观测的频率并将它们按r排序? - How to know the frequency of each observation in a column and sort them in r? R 中的行到列观察 - Observation in Row to Column in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM