我有一个数据集,其中列是不同的站点,前两行提供了纬度和经度值。我想转置这些数据,以便每个站点现在都是一行,列中包含纬度和经度值。
我正在尝试使用 执行此操作pivot_longer,但迄今为止尚未成功,因为从示例中我不清楚如何指示哪些字段应该是新的行和列。
df <- data.frame(
sites = c("lat", "lon"),
A = c(10, 20),
B = c(12, 18),
C = c(14, 17),
D = c(21, 12),
E = c(3, 23)) %>%
# transpose with sites in 1st column (A-E on different rows) and lat/lon values in seperate columns
pivot_longer(cols = c(2:6),
names_to = c("lat", "lon"),
values_to = "sites")
Error in `build_longer_spec()`:
! If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.
Run `rlang::last_error()` to see where the error occurred.
Run Code Online (Sandbox Code Playgroud)
transpose我们这里可能需要
library(data.table)\ndata.table::transpose(setDT(df), make.names = "sites")\nRun Code Online (Sandbox Code Playgroud)\n-输出
\n lat lon\n <num> <num>\n1: 10 20\n2: 12 18\n3: 14 17\n4: 21 12\n5: 3 23\nRun Code Online (Sandbox Code Playgroud)\n如果我们需要列名作为每行的标识符
\n data.table::transpose(setDT(df), make.names = "sites", keep.names = "grp")\n grp lat lon\n <char> <num> <num>\n1: A 10 20\n2: B 12 18\n3: C 14 17\n4: D 21 12\n5: E 3 23\nRun Code Online (Sandbox Code Playgroud)\n如果我们想使用tidyverse,则将形状重塑为“长”,然后重塑为“宽”pivot_wider
library(dplyr)\nlibrary(tidyr)\ndf %>% \n pivot_longer(cols = -sites, names_to = 'grp') %>% \n pivot_wider(names_from = sites, values_from = value)\n# A tibble: 5 \xc3\x97 3\n grp lat lon\n <chr> <dbl> <dbl>\n1 A 10 20\n2 B 12 18\n3 C 14 17\n4 D 21 12\n5 E 3 23\nRun Code Online (Sandbox Code Playgroud)\n