gpt4 book ai didi

重命名多列并在 R 中使用 dplyr 进行收集

转载 作者:行者123 更新时间:2023-12-04 10:45:51 25 4
gpt4 key购买 nike

我正在尝试找到一种使用 tidyverse 重命名多个列的便捷方法。说我有一个小问题

df <- tibble(a = 1, b = 2, tmp_2000 = 23, tmp_2001 = 22.1, tmp_2002 = 25, pre_2000, pre_2001, pre_2002)

# A tibble: 1 x 8
a b tmp_2000 tmp_2001 tmp_2002 pre_2000 pre_2001 pre_2002
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2 23 22.1 25 100 103 189

temppre 代表温度和降水量。我想以整洁的形式重组此表,即 temperature 一列,precipitations 一列,每一行都是年份的相应值。

现在我找到的唯一选择就是做这样的事情

df <- df %>%
select(-starts_with("pre"))

names(df)[3:5] <- substr(names(df)[3:5],5,8)

df<-df %>%
gather(`2000`:`2002`,key = "year",value="temp") %>%
mutate("year" = as.integer(year))

# A tibble: 3 x 4
a b year temp
<dbl> <dbl> <int> <dbl>
1 2 2000 23
1 2 2001 22.1
1 2 2002 25

这并不好,因为我需要对降水做同样的事情,然后连接两个表。将来我会得到更多的天气变量,这个过程很快就会变得很痛苦。

有没有人知道如何使用 tidyverse 更有效地做到这一点?

谢谢,

PS:我看到的唯一类似的帖子提到重新编码变量(使用 mutate_at),或使用我上面显示的 names 重命名列。

最佳答案

你可以这样做:

library(tidyverse)
df %>%
gather(measure, value, -a, -b) %>%
separate(measure, into = c("type", "year"), sep = "_") %>%
mutate(type = case_when(type == "tmp" ~ "temp", type == "pre" ~ "precip")) %>%
spread(type, value)
# a b year precip temp
# 1 1 2 2000 100 23
# 2 1 2 2001 103 22.1
# 3 1 2 2002 189 25

我们首先以长格式收集所有数据,然后将年份与测量值分开,然后更改测量值的名称,最后将数据传播回宽格式。

关于重命名多列并在 R 中使用 dplyr 进行收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51698191/

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