【发布时间】:2018-08-25 06:58:21
【问题描述】:
对于数据框,我需要逐行查找从第 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)))
这会导致“错误:所有嵌套列必须具有相同数量的元素。”。
【问题讨论】: