来自多列的 Pivot_longer 成对

Rai*_*dho 1 r dplyr tidyr

有一个这样的数据集

df <- data.frame(
  Pseudonym = c("aa", "bb"),
  KE_date_1 = c("2022-04-01", "2022-04-03"),
  KE_content_2 = c("high pot", "high pot"),
  KE_date_3 = c("2022-08-01", "2022-08-04"),
  KE_content_4 = c("high pot return", "high pot return")
)
Run Code Online (Sandbox Code Playgroud)
Pseudonym | KE_date_1 |   KE_content_2| KE_date_3  |  KE_content_4
--------------------------------------------------------------------
aa        | 2022-04-01|     high pot  | 2022-08-01 | high pot return
bb        | 2022-04-03|     high pot  | 2022-08-04 | high pot return
Run Code Online (Sandbox Code Playgroud)

具有标识符(不同的假名)和成对数据列(日期 + 文本)的列。数据列具有递增的后缀。..1 和 ..2 属于同一组,等等。

由此需要一个转换后的长数据集,其中假名不再明显。

df2 <- data.frame(
  Pseudonym = c("aa", "aa", "bb", "bb"),
  KE_date = c("2022-04-01", "2022-08-01", "2022-04-03", "2022-08-04"),
  KE_content = c("high pot", "high pot return", "high pot", "high pot return")
)

Run Code Online (Sandbox Code Playgroud)
Pseudonym |  KE_date     |  KE_content
-------------------------------------------
aa        |  2022-04-01  |  high pot
aa        |  2022-08-01  |  high pot return
bb        |  2022-04-03  |  high pot
bb        |  2022-08-04  |  high pot return
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?谢谢。

Dav*_*ong 5

您可以使用pivot_longer()来自tidyr. 您可以指定names_pattern参数来捕获名称末尾的下划线和数字之前的所有内容。该参数是一个正则表达式,用于标识透视变量的唯一名称。在下面的示例中,我使用"(.*)_\\\\d$". 在正则表达式术语中,.匹配任何字符。星号告诉正则表达式继续包含字符,直到与搜索字符串不匹配为止。例如,在字符串 中"aabbc",匹配“a”将仅标识第一个字符,但匹配“a*”将匹配前两个字符。匹配“.” 将再次仅识别第一个字符,但匹配".*"将匹配所有 5 个字符。在 中names_pattern,您将要提取的信息放在括号中。在我使用的正则表达式中,捕获了下划线和末尾数字之前的所有内容(字符串的末尾用美元符号标记),因此从变量名称中"KE_content_1", "KE_date_2", "KE_content_3", "KE_date_4",正则表达式将返回"KE_content", "KE_date", "KE_content", "KE_date"。然后,使用names_to = ".value"会将正则表达式返回的每个唯一值放入names_pattern不同的列中。有关pivot_longer()工作原理的更多信息,您可以查看包装中的旋转小插图tidyr。有关正则表达式的更多信息,您可以谷歌正则表达式教程。 这个看起来还不错啊。

\n
input <- data.frame(\n  Pseudonym = c("aa", "bb"),\n  KE_date_1 = c("2022-04-01", "2022-04-03"),\n  KE_content_2 = c("high pot", "high pot"),\n  KE_date_3 = c("2022-08-01", "2022-08-04"),\n  KE_content_4 = c("high pot return", "high pot return")\n)\n\nlibrary(dplyr)\nlibrary(tidyr)\ninput %>% \n  pivot_longer(starts_with("KE"), \n               names_pattern="(.*)_\\\\d$", \n               names_to = ".value")\n#> # A tibble: 4 \xc3\x97 3\n#>   Pseudonym KE_date    KE_content     \n#>   <chr>     <chr>      <chr>          \n#> 1 aa        2022-04-01 high pot       \n#> 2 aa        2022-08-01 high pot return\n#> 3 bb        2022-04-03 high pot       \n#> 4 bb        2022-08-04 high pot return\n
Run Code Online (Sandbox Code Playgroud)\n

创建于 2023-08-28,使用reprex v2.0.2

\n