【发布时间】:2021-04-13 19:48:33
【问题描述】:
我遇到了一个非常奇怪的数据框结构,这是一个例子
# A tibble: 3 x 4
ColName...1 Sample1 ColName...2 Sample2
<chr> <dbl> <chr> <dbl>
1 A 1 A 4
2 B 2 B 5
3 NA NA C 6
谁的代码可以从:
ColName...1 <- c("A","B",NA)
Sample1 <- c(1,2,NA)
ColName...2 <- c("A","B","C")
Sample2 <- c(4,5,6)
我希望将我的数据转换为更传统的格式:
A B C Sample
1 1 2 NA 1
2 4 5 6 2
可以通过以下方式获得:
# Desired output
df <- data.frame(c(1,4),c(2,5),c(NA,6),c(1,2))
colnames(df) <- c("A","B","C","Sample")
df
换句话说,我需要告诉 R ColName...1、ColName...2 等是包含数据框名称的变量,我需要将列 Sample1、Sample2 等...转置所以它们是这个数据框中的行。我该如何编码?
编辑: 我实际使用的数据框更加混乱。这是它的外观:
# A tibble: 10 x 6
Element...1 GeoPT8 Element...3 GeoPT9 Element...5 GeoPT10
<chr> <dbl> <chr> <dbl> <chr> <dbl>
1 SiO2 66 SiO2 59 SiO2 64
2 TiO2 67 TiO2 63 TiO2 69
3 Al2O3 69 Al2O3 63 Al2O3 71
4 Fe2O3 71 Fe2O3 68 Fe2O3 74
5 Fe(II)O 16 Fe(II)O 17 MnO 73
6 MnO 70 MnO 68 MgO 70
7 MgO 69 MgO 64 CaO 73
8 CaO 70 CaO 65 Na2O 73
9 Na2O 71 Na2O 66 P2O5 60
10 K2O 69 K2O 64 LOI 54
获取此数据框的代码:
df <- structure(list(Element...1 = c("SiO2", "TiO2", "Al2O3", "Fe2O3", "Fe(II)O", "MnO", "MgO", "CaO", "Na2O", "K2O"),
GeoPT8 = c(66,67, 69, 71, 16, 70, 69, 70, 71, 69),
Element...3 = c("SiO2", "TiO2", "Al2O3", "Fe2O3", "Fe(II)O", "MnO", "MgO", "CaO", "Na2O", "K2O"),
GeoPT9 = c(59, 63, 63, 68, 17, 68, 64, 65, 66, 64),
Element...5 = c("SiO2", "TiO2", "Al2O3", "Fe2O3", "MnO", "MgO", "CaO", "Na2O", "P2O5", "LOI"),
GeoPT10 = c(64, 69, 71, 74, 73, 70, 73, 73, 60, 54)), row.names = c(NA, -10L),
class = c("tbl_df", "tbl", "data.frame"))
可以看到,列 Element...1 和 Element...5 不匹配(Element...5 包含 MnO,但 Element...1 不包含)。如何对 R 说包含 GeoPT8 键的列是 Element...1 列,包含 GeoPT10 键的列是 Element...5 等等?
【问题讨论】:
标签: r dataframe data-manipulation