繁体   English   中英

使用 tidyverse 在 R 中进行数据整理?

[英]Data Wrangling in R using tidyverse?

所以我有这个数据集 主要转换是旋转表格,所以人口名称在第一列,名称是每列的标题(它们被重命名,例如叶绿素被重命名为 CHLa)。 表被旋转和重命名后的另一个变化是,每一行都被复制到指定的数量,所以在预览中,如果你注意到,AK 被复制了 8 次,NU 被复制了两次,依此类推。 谁能帮我完成这个? 谢谢!

我们可以使用pivot_longer转换为长格式,然后执行pivot_wider

library(tidyr)
library(dplyr)
library(stringr)
df1 %>% 
  filter(str_detect(name, 'Chlorophyll')) %>%
  pivot_longer(cols = -name, names_to = "POP") %>%      
  pivot_wider(names_from = name, values_from = value)

数据

df1 <- structure(list(AK = c(2.06938085, 0.06230826, 2.48330742, 0.77990199, 
0.05352413, 2.42978332, 0.32111359, -0.31824945, -0.76257673, 
0.21244649), NU = c(0.94342952, 0.06967302, 1.18308591, 0.24512465, 
0.05954595, 1.12353996, 0.3282527, 0.0332011, 0.10143732, 0.01747852
), GR = c(2.02611122, 0.04936086, 2.41093187, 0.45293345, 0.04685186, 
2.36408, -0.2601983, -0.5992214, -0.53467979, 0.07776527), LB = c(1.54587253, 
0.26267895, 1.74803992, 0.67839487, 0.22805005, 1.51998983, -0.25436427, 
-0.07033478, 0.09848198, 0.07864418), NF = c(1.63438226, 0.19021245, 
1.81304267, 0.69796724, 0.1629694, 1.65007327, 0.21143971, 0.32577614, 
0.29918981, 0.08665113), ST = c(2.40265686, 1.16806181, 2.66182316, 
1.7417354, 0.89450362, 1.76731954, -0.38944296, -0.31842728, 
-0.27451047, 0.09962626), NS = c(1.143188447, 0.070796679, 1.393892288, 
0.447486223, 0.059898949, 1.333993367, 0.003421558, 0.020280698, 
-0.044788628, 0.086701809), NB = c(1.79361422, 0.23087077, 2.34315343, 
0.8995402, 0.16849883, 2.17465466, -0.30522065, -0.43764352, 
-0.64518845, 0.07564453), ME = c(1.6936173, 0.1307856, 2.0172089, 
0.7113195, 0.1135671, 1.9036418, -0.9033899, -0.7945115, -0.8507709, 
0.1036442), IC = c(2.28296799, 0.14749662, 2.51693005, 0.89241081, 
0.13475936, 2.38217072, 0.48013856, 0.59088701, 0.60322486, 0.05169639
), FI = c(0.55358516, 0.05694769, 0.75707975, 0.20722915, 0.04236526, 
0.71471448, 0.42658058, -0.01849223, -0.22192967, 0.08643648), 
    name = c("Present.Surface.Chlorophyll.Lt.max", "Present.Surface.Chlorophyll.Lt.min", 
    "Present.Surface.Chlorophyll.Max", "Present.Surface.Chlorophyll.Mean", 
    "Present.Surface.Chlorophyll.Min", "Present.Surface.Chlorophyll.Range", 
    "Present.Surface.Cloud.cover.Max", "Present.Surface.Cloud.cover.Mean", 
    "Present.Surface.Cloud.cover.Min", "Present.Surface.Current.Velocity.Lt.max"
    )), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6", "7", "8", "9", "10"))

我认为您可以使用 tidyverse 中的 pivot_wider 和 pivot_longer 函数: https ://tidyr.tidyverse.org/articles/pivot.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM