gpt4 book ai didi

r 将具有模式的列名从宽数据集转换为长数据集

转载 作者:行者123 更新时间:2023-12-02 02:58:00 25 4
gpt4 key购买 nike

让我们假设一个像下面这样的数据集。

 ID   Gender  ColA_1  ColB_1 ColC_1__1 ColC_1__2 ColA_2  ColB_2 ColC_2__1 ColC_2__2 
1 Male No Yes Yes No No Yes No No
2 Female Yes No Yes No No Yes Yes No

我喜欢做的是像下面这样转换这个数据集

 ID Index  Gender  ColA  ColB   ColC_1 ColC_2  
1 1 Male No Yes Yes No
1 2 Male No Yes No No
2 1 Female Yes No Yes No
2 2 Female No Yes Yes No

不知道如何执行此操作,需要帮​​助。提前致谢。

最佳答案

这是一个带有pivot_longer的选项

library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
rename_at(vars(starts_with('ColC')), ~ str_replace(., "_(\\d+)__(\\d+)",
"\\2_\\1")) %>%
pivot_longer(cols = 3:ncol(.), names_to = c(".value", "Index"),
names_sep="_")
# A tibble: 4 x 7
# ID Gender Index ColA ColB ColC1 ColC2
# <int> <chr> <chr> <chr> <chr> <chr> <chr>
#1 1 Male 1 No Yes Yes No
#2 1 Male 2 No Yes No No
#3 2 Female 1 Yes No Yes No
#4 2 Female 2 No Yes Yes No

数据

df1 <- structure(list(ID = 1:2, Gender = c("Male", "Female"), ColA_1 = c("No", 
"Yes"), ColB_1 = c("Yes", "No"), ColC_1__1 = c("Yes", "Yes"),
ColC_1__2 = c("No", "No"), ColA_2 = c("No", "No"), ColB_2 = c("Yes",
"Yes"), ColC_2__1 = c("No", "Yes"), ColC_2__2 = c("No", "No"
)), class = "data.frame", row.names = c(NA, -2L))

关于r 将具有模式的列名从宽数据集转换为长数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60687769/

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