我有这个数据框
df <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), Type = c("Date", "Text", "Value", "Text", "Date", "Value", "Value", "Text", "Date" ), Parameter = c("2020-2-3", "String", 9.99, "String", "2020-2-4", 0, 10, "String", "2020-2-5")), class = "data.frame", row.names = c(NA, -9L))我想要这个
ID Type Parameter Date
1 Text String 2020-2-3
1 Value 9.99 2020-2-3
2 Text String 2020-2-4
2 Value 0 2020-2-4
3 Value 10 2020-2-5
3 Text String 2020-2-5我的想法是
pivot_wider(names_from = Type, values_from = Parameter)
但它会透视所有列
发布于 2021-08-26 10:28:00
在新列中获取Type = Date值,并使用每个ID的先前值对它们执行fill操作。
library(dplyr)
library(tidyr)
df %>%
mutate(Date = replace(Parameter, Type != 'Date', NA)) %>%
group_by(ID) %>%
fill(Date, .direction = 'updown') %>%
ungroup %>%
filter(Type != 'Date')
# ID Type Parameter Date
# <int> <chr> <chr> <chr>
#1 1 Text String 2020-2-3
#2 1 Value 9.99 2020-2-3
#3 2 Text String 2020-2-4
#4 2 Value 0 2020-2-4
#5 3 Value 10 2020-2-5
#6 3 Text String 2020-2-5https://stackoverflow.com/questions/68936325
复制相似问题