r - 使用一个指示更新日期的变量将时间相关变量转换为长格式

标签 r dataframe pivot reshape

我正在尝试使用一个指示更新日期的变量将数据转换为长格式。

我有以下变量:

  1. 基线温度变量“temp_b”;
  2. 随时间变化的温度变量“temp_v”和
  3. 更新变化变量的天数“n_days”。 我想使用结转方法创建长格式,最长跟进时间为 5 天。

数据示例

df <- structure(list(id=1:3, temp_b=c(20L, 7L, 7L), temp_v=c(30L, 10L, NA), n_days=c(2L, 4L, NA)), class="data.frame", row.names=c(NA, -3L))

  #   id temp_b temp_v n_days
  # 1  1     20     30      2
  # 2  2      7     10      4
  # 3  3      7     NA     NA

df_long <- structure(list(id=c(1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3),
                          days_cont=c(1,2,3,4,5, 1,2,3,4,5, 1,2,3,4,5),
                          long_format=c(20,30,30,30,30,7,7,7,10,10,7,7,7,7,7)),
                          class="data.frame", row.names=c(NA, -15L))

  #    id days_cont long_format
  # 1   1         1          20
  # 2   1         2          30
  # 3   1         3          30
  # 4   1         4          30
  # 5   1         5          30
  # 6   2         1           7
  # 7   2         2           7
  # 8   2         3           7
  # 9   2         4          10
  # 10  2         5          10
  # 11  3         1           7
  # 12  3         2           7
  # 13  3         3           7
  # 14  3         4           7
  # 15  3         5           7

最佳答案

您可以使用 tidyr::uncount() 重复每行 5 次:

library(dplyr)

df %>%
  tidyr::uncount(5) %>%
  group_by(id) %>%
  transmute(days_cont = 1:n(),
            temp = ifelse(row_number() < n_days | is.na(n_days), temp_b, temp_v)) %>%
  ungroup()

# # A tibble: 15 × 3
#       id days_cont  temp
#    <int>     <int> <int>
#  1     1         1    20
#  2     1         2    30
#  3     1         3    30
#  4     1         4    30
#  5     1         5    30
#  6     2         1     7
#  7     2         2     7
#  8     2         3     7
#  9     2         4    10
# 10     2         5    10
# 11     3         1     7
# 12     3         2     7
# 13     3         3     7
# 14     3         4     7
# 15     3         5     7

关于r - 使用一个指示更新日期的变量将时间相关变量转换为长格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73538698/

相关文章:

r - 设置数据框列表列表的格式

r - 聚合数据框每一列的所有唯一值

r - 如何仅保留数据框中的最高重复值?

python - 使用字典通过引用 Pandas 来乘以列

python - 为什么我在切片数据框中看到所有原始索引元素?

python - pandas 的 "pivot"操作的精确逆运算

r - 在facet_wrap图中添加 "floating"轴标签

sql - 如何为 PIVOT 聚合指定 GROUP BY

python - 高斯消元法 - 在 python 中使用切片进行旋转

R和postgreSQL表操作