簡體   English   中英

根據其他數值列中的數字范圍查找數值列的最小值和最大值

[英]Find the minimum and maximum values of a numeric column based on the range of numbers in other numeric column

我在下面有 dataframe,我想添加 3 個新列。 第一列將命名為years_5 ,它將包含諸如"1951-1955""1955-1959"等值。在找到列year的最小值后,加 5 年將從該值開始。 這里最小的年份是1951 第二列將命名為Scope_min並將包含相對years_5單元格的最小 scope 值,第三列將命名為Scope_max並將包含相對years_5單元格的最大 scope 值。 例如,第一行將如下所示:

year Scope   years_5 Scope_min Scope_max
1 1951     4 1951-1955         3         5

df<-structure(list(year = c(1951, 1954, 1955, 1957, 1958, 1960, 1961, 
1962, 1963, 1964, 1965, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 
1974, 1975, 1976, 1977, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 
1986, 1988, 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 
1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019), 
    Scope = c(4, 3, 5, 27, 6, 13, 6, 6, 24, 1, 21, 24, 32, 57, 
    18, 1, 43, 39, 8, 58, 68, 78, 7, 20, 26, 4, 12, 19, 8, 37, 
    35, 51, 209, 478, 395, 355, 453, 457, 262, 148, 196, 180, 
    367, 283, 360, 414, 175, 330, 314, 446, 428, 163, 213, 165, 
    307, 231, 53, 189, 18, 104, 39)), class = "data.frame", row.names = c(NA, 
-61L))

最初,我按年份排列數據。 在您的示例數據中已經存在,但在您的真實數據中可能並非如此。 接下來,我cut這些組分成五年的部分。 我為最后一組留下了一個例外(可能不到五年)。

然后我創建了新變量、 fiveYearsScope_minScope_max 最后,取消嵌套,以便您擁有所有數據和基於組的信息。

library(tidyverse)

df1 <- df %>% arrange(year) %>% 
  mutate(five_years = cut(year, ceiling(nrow(df)/5),
                          include.lowest = T,
                          ordered_result = T)) %>% 
  group_by(five_years) %>% 
  nest() 

df2 <- map_dfr(df1$data,
               ~.x %>% 
                 mutate(fiveYears = paste0(min(year), "-", max(year)),
                        Scope_min = min(Scope),
                        Scope_max = max(Scope))
               ) %>% unnest(c(fiveYears, Scope_min, Scope_max))

head(df2, n = 10)
# # A tibble: 10 × 5
#     year Scope fiveYears Scope_min Scope_max
#    <dbl> <dbl> <chr>         <dbl>     <dbl>
#  1  1951     4 1951-1955         3         5
#  2  1954     3 1951-1955         3         5
#  3  1955     5 1951-1955         3         5
#  4  1957    27 1957-1961         6        27
#  5  1958     6 1957-1961         6        27
#  6  1960    13 1957-1961         6        27
#  7  1961     6 1957-1961         6        27
#  8  1962     6 1962-1965         1        24
#  9  1963    24 1962-1965         1        24
# 10  1964     1 1962-1965         1        24 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM