gpt4 book ai didi

r - pivot_longer 并返回 NA

转载 作者:行者123 更新时间:2023-12-02 15:43:45 27 4
gpt4 key购买 nike

简单的 pivot_longer 问题。鉴于:

library(tidyverse)
df <- data.frame(id = c(1),
test_date = as.Date("01/01/1998", "%d/%m/%Y"),
test_result = c("yes"),
exit_date = as.Date("01/02/1998", "%d/%m/%Y"),
dob_date = as.Date("01/01/1997", "%d/%m/%Y"),
exit_result_1 = c(10),
exit_result_2 = c(4),
exit_result_3 = c(2))
df
# id test_date test_result exit_date dob_date exit_result_1 exit_result_2 exit_result_3
# 1 1 1998-01-01 yes 1998-02-01 1997-01-01 10 4 2

我要:

#   id test_result exit_result_1 exit_result_2 exit_result_3 date_name      dates
# 1 1 yes NA NA NA test_date 1998-01-01
# 2 1 <NA> 10 4 2 exit_date 1998-02-01
# 3 1 <NA> NA NA NA dob_date 1997-01-01

类似的东西

pivot_longer(df, cols = matches('date'), 
names_to = "date_name", values_to = "dates")

但我想返回 NA。有什么建议吗?谢谢

最佳答案

可以在names_to中设置".value"来表示定义输出列名称的列名称对应的组成部分。在这种情况下,必须提供 names_sepnames_pattern 之一来指定应如何拆分列名。

df %>%
pivot_longer(
-id,
names_to = c("date_name", ".value"),
names_pattern = "([^_]+)_(.+)"
)

# # A tibble: 3 × 7
# id date_name date result result_1 result_2 result_3
# <dbl> <chr> <date> <chr> <dbl> <dbl> <dbl>
# 1 1 test 1998-01-01 yes NA NA NA
# 2 1 exit 1998-02-01 NA 10 4 2
# 3 1 dob 1997-01-01 NA NA NA NA

为了比较,原始数据集看起来像

df
# id test_date test_result exit_date dob_date exit_result_1 exit_result_2 exit_result_3
# 1 1 1998-01-01 yes 1998-02-01 1997-01-01 10 4 2

关于r - pivot_longer 并返回 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75084044/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com