我有一个数据集,看起来像这个例子
name test marks name.1 test.1 marks.1 name.2 test.2 marks.2 name.3 test.3 marks.3
Jon math 456 Ria history 564 Nia math 456 Tom physics 567
然而,我的原始数据集非常广泛,大约有700列。我希望重塑这个数据集,它在R 中从一行扩展到多行
我想要一个看起来像的输出
name test marks
Jon math 456
Ria history 564
Nia math 456
Tom physics 567
我提到将多组列(宽格式(重塑为单列(长格式(,将r中的一行转变为多行,甚至更多,但无法找到合适的解决方案。
我将非常感谢的任何帮助
您可以在names_to
中设置".value"
,并提供names_sep
或names_pattern
之一来指定列名的拆分方式。
library(tidyr)
df %>%
pivot_longer(everything(), names_to = c(".value", NA), names_pattern = "([^.]+)\.?(.*)")
# # A tibble: 4 × 3
# name test marks
# <chr> <chr> <int>
# 1 Jon math 456
# 2 Ria history 564
# 3 Nia math 456
# 4 Tom physics 567
数据
df <- structure(list(name = "Jon", test = "math", marks = 456L, name.1 = "Ria",
test.1 = "history", marks.1 = 564L, name.2 = "Nia", test.2 = "math",
marks.2 = 456L, name.3 = "Tom", test.3 = "physics", marks.3 = 567L), class = "data.frame", row.names = c(NA, -1L))