gpt4 book ai didi

r - 在 R 中的类似宽表上使用 pivot_longer?

转载 作者:行者123 更新时间:2023-12-04 14:48:24 24 4
gpt4 key购买 nike

我有一些看起来像这样的数据

color   value_morning   quality_morning value_evening   quality_evening value_night quality_night
red 10 good 9 good 10 good
blue 7 bad 8 great 10 great
green 7 bad 8 good 6 bad

我正在尝试使用 pivot_longer() (或任何其他 tidy 方法)将其转换为:

color   value   time
red 10 morning
blue 7 morning
green 7 morning
red 9 evening
blue 8 evening
green 8 evening
red 10 night
blue 10 night
green 6 night

我不需要 quality_数据,只是 value_数据。

我尝试创建一个看起来像 labels <- c("value_morning", "value_evening", "value_night") 的矢量正在运行 df %>% pivot_longer(cols = labels)但这没有用。感谢您的帮助!

最佳答案

我们删除 quality 列,然后执行 pivot_longer

library(dplyr)
library(tidyr)
df1 %>%
select(-starts_with('quality')) %>%
pivot_longer(cols = -color, names_to = c(".value", "time"),
names_pattern = "(.*)_(.*)")

-输出

# A tibble: 9 × 3
color time value
<chr> <chr> <int>
1 red morning 10
2 red evening 9
3 red night 10
4 blue morning 7
5 blue evening 8
6 blue night 10
7 green morning 7
8 green evening 8
9 green night 6

数据

df1 <- structure(list(color = c("red", "blue", "green"), value_morning = c(10L, 
7L, 7L), quality_morning = c("good", "bad", "bad"), value_evening = c(9L,
8L, 8L), quality_evening = c("good", "great", "good"), value_night = c(10L,
10L, 6L), quality_night = c("good", "great", "bad")),
class = "data.frame", row.names = c(NA,
-3L))

关于r - 在 R 中的类似宽表上使用 pivot_longer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69533124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com