我的数据合并如下:
X | 身份证 | 日期_度量 | 月 | 年龄 | 编译的指标 |
---|---|---|---|---|---|
25 | 2063 | 2016-12-28 | 12 | 63.7 | 258 不适用 |
13274 | 2063 | 2016-12-28 | 12 | 63.7 | NA 2948 |
而不是拥有
X | 身份证 | 日期_度量 | 月 | 年龄 | 高度 | 身体质量 |
---|---|---|---|---|---|---|
25 | 2063 | 2016-12-28 | 12 | 63.7 | 258 | 2948 |
Compile_metrics 具有特色。
我已经尝试过这段代码,但输出完全混乱,我不知道为什么......
#first table
combine_height_body_mass <- function(df) {
df %>%
group_by(ID) %>%
slice_max(order_by = date_measure) %>%
mutate(combined_metrics = paste(height, body_mass)) %>%
select(all_of(c("X","ID","date_measure","Month","Age","height", "body_mass")))
}
final_df <- combine_height_body_mass(combined_dt)
#Compile rows
combine_height_body_mass <- function(df) {
combined_df <- df %>%
group_by(ID) %>%
slice_max(order_by = date_measure) %>%
select(
X,
ID,
date_measure,
Month,
Age,
height,
body_mass
)
combined_df <- combined_df %>%
mutate(compiled_metrics = paste(height, body_mass))
return(combined_df)
}
final_df <- combine_height_body_mass(combined_dt)
PS:身高和体重应该是数字
谢谢
假设数据框如末尾注释所示,以可重现的形式。
删除 X 列,将
compiled_metrics
分成单独的字段
并取组中所有值的最小值,除去 NA。
library (dplyr)
library (tidyr)
dat1 %>%
select(!X) %>%
separate(compiled_metrics, c("height", "body_mass"), convert = TRUE) %>%
summarize(across(everything(), ~ min(.x, na.rm = TRUE)), .by = ID:Age)
## ID date_measure Month Age height body_mass
## 1 2063 2016-12-28 12 63.7 258 2948
数据1<- data.frame( X = c(25L, 13274L), ID = c(2063L, 2063L), date_measure = c("2016-12-28", "2016-12-28"), Month = c(12L, 12L), Age = c(63.7, 63.7), compiled_metrics = c("258 NA", "NA 2948") )