我有一個具有這種結構的資料集(向調查受訪者提出了很多問題),我想從寬到長重塑:
library(tidyverse)
df_wide <-
tribble(
~resp_id, ~question_1_info, ~question_1_answer, ~question_2_info, ~question_2_answer,
1, "What is your eye color?", 1, "What is your hair color?", 2,
2, "Are you over 6 ft tall?", 1, "", NA,
3, "What is your hair color?", 0, "Are you under 40?", 1
)
這是我想要的輸出:
df_long <-
tribble(
~resp_id, ~question_number, ~question_text, ~question_answer,
1, 1, "What is your eye color?", 1,
1, 2, "What is your hair color?", 2,
2, 1, "Are you over 6 ft tall?", 1,
2, 2, "", NA,
3, 1, "What is your hair color?", 0,
3, 2, "Are you under 40?", 1
)
我在讓多個類的列一起作業時遇到問題。這是我嘗試過的:
df_wide %>%
pivot_longer(
cols = !resp_id,
names_to = c("question_number"),
names_prefix = "question_",
values_to = c("question_text", "question_answer")
)
我無法獲得names_toornames_prefix和的正確配置values_to。
uj5u.com熱心網友回復:
我們可以names_pattern在重新排列列名中的子字串后使用
library(dplyr)
library(tidyr)
library(stringr)
df_wide %>%
# rename the columns by rearranging the digits at the end
# "_(\\d )(_.*)" - captures the digits (\\d ) after the _
# and the rest of the characters (_.*)
# replace with the backreference (\\2, \\1) of captured groups rearranged
rename_with(~ str_replace(., "_(\\d )(_.*)", "\\2_\\1"), -resp_id) %>%
pivot_longer(cols = -resp_id, names_to = c( ".value", "question_number"),
names_pattern = "(.*)_(\\d $)")
-輸出
# A tibble: 6 × 4
resp_id question_number question_info question_answer
<dbl> <chr> <chr> <dbl>
1 1 1 "What is your eye color?" 1
2 1 2 "What is your hair color?" 2
3 2 1 "Are you over 6 ft tall?" 1
4 2 2 "" NA
5 3 1 "What is your hair color?" 0
6 3 2 "Are you under 40?" 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430465.html
