首页 > 解决方案 > R:列数未知的行的最小值和最大值

问题描述

对于数据框,我需要逐行查找从第 2 列开始的未知列数的最小值和最大值。这是一个例子:

library(tidyverse)

# test data
(test_data <- tibble(id = c(1:9), 
                     x = runif(9), 
                     x2 = runif(9),
                     x3 = runif(9)))
samples = 100    

# This example, which specifies the column names, correctly finds the min and max values by row
(test_1 <- test_data %>% 
  rowwise() %>%
  mutate(min_val = min(x, x2, x3), max_val = max(x, x2, x3)))

# This example does not
(test_2 <- test_data %>% 
    rowwise() %>%
    mutate(min_val = min(x:x3), max_val = max(x:x3)))

我真正想做的是

mutate(min_val = min([,2:samples+1]), max_val = max([,2:samples+1])))

因为(1)我希望保留 id 列(以便稍后与另一个数据框连接),并且(2)按列位置指定似乎是一种明显的方法,因为我不关心列名并且样本可能很大。

谢谢!

编辑示例

这(如建议的)

test_data %>%
  nest(-id) %>%                         # nest rest of columns apart from id
  mutate(min_val = map(data, min),      # get min and max
         max_val = map(data, max)) %>%
  unnest()   

在原始测试数据上工作。然而,现实世界的数据有重复的 id,例如

(test_data <- tibble(id = c(1:9, 1:9), 
                     x = runif(18), 
                     x2 = runif(18),
                     x3 = runif(18)))

这会导致“错误:所有嵌套列必须具有相同数量的元素。”。

标签: rdplyr

解决方案


一个可能的tidyverse解决方案是nest您拥有的任何列,除了id,然后用于map获取minmax。您无需指定任何列名:

library(tidyverse)

# test data
(test_data <- tibble(id = c(1:9), 
                     x = runif(9), 
                     x2 = runif(9),
                     x3 = runif(9)))
samples = 100    

test_data %>%
  nest(-id) %>%                         # nest rest of columns apart from id
  mutate(min_val = map(data, min),      # get min and max
         max_val = map(data, max)) %>%
  unnest()                              # unnest columns

# # A tibble: 9 x 6
#      id min_val max_val      x     x2    x3
#   <int>   <dbl>   <dbl>  <dbl>  <dbl> <dbl>
# 1     1  0.0217   0.239 0.130  0.0217 0.239
# 2     2  0.125    0.814 0.625  0.814  0.125
# 3     3  0.281    0.770 0.331  0.770  0.281
# 4     4  0.123    0.868 0.123  0.644  0.868
# 5     5  0.149    0.340 0.149  0.340  0.337
# 6     6  0.496    0.865 0.596  0.865  0.496
# 7     7  0.0766   0.984 0.0766 0.656  0.984
# 8     8  0.272    0.926 0.702  0.926  0.272
# 9     9  0.433    0.912 0.912  0.433  0.590

在有多个 id 的情况下,您可以使用:

test_data %>%
  mutate(row_id = row_number()) %>%     # create a row identifier
  nest(-id, -row_id) %>%                # nest rest of columns apart from id and row id
  mutate(min_val = map(data, min),      # get min and max
         max_val = map(data, max)) %>%
  unnest()                              # unnest columns

推荐阅读