r - 使用 tidyverse 在 R 中进行数据整理?
问题描述
所以我有这个数据集主要的转换是旋转表格,所以人口名称在第一列,名称是每列的标题(并且它们被重命名,因此叶绿素被重命名为 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"))
推荐阅读
- spring-boot - spring boot 2 + netty + servlet.context-path + 不工作
- c# - 从 oracle forms 6i 调用 C# DLL
- javascript - 如何从侧边栏显示单击的项目到第一个位置,剩余的列表被隐藏并悬停显示列表
- python - 使用“时间”获取上午或下午
- wordpress - 如何在 WordPress 的作者长传中添加“阅读更多”
- filter - ublock, adblock: block elements with dynamical id
- r - R not recognizing my alternative GCC compiler after config updates?
- javascript - I want to get latitude longitude height of my mouse at the bottom of the cesium screen
- python - python Serialport写入十进制
- ruby - 与 ruby net/ssh gem 建立连接后如何进行 SSH