R 中的数据转换,一列重复行

问题描述 投票:0回答:1
安装 fish_ID G R Y
0 1 136 140 249 68
3 1 510 7 108 13

我想将上面的数据转换为下面的数据:

fish_ID 颜色 inst_0 inst_3
1 136 510
1 G 140 7
1 R 249 108
1 Y 68 13

我尝试使用 pivot longer 函数,但没有用。感谢您的帮助。谢谢大家!

r dataframe tidyr transformation
1个回答
0
投票

您可以使用

gather()
spread()

数据

df <- data.frame(
  inst = c(0, 3),
  fish_ID = c(1, 1),
  B = c(136, 510),
  G = c(140, 7),
  R = c(249, 108),
  Y = c(68, 13)
)
library(tidyverse)

df_new <- df %>%
  gather(key = "Color", value = "value", B:Y)

df_final <- df_new %>%
  spread(key = "inst", value = "value") %>%
  select(fish_ID, Color, inst_0 = "0", inst_3 = "3")
© www.soinside.com 2019 - 2024. All rights reserved.