I have a dataframe containing three columns, two of which can contain either numeric values or lists. I would like to add additional columns containing the min / max values of each of these two columns. For example, my data frame may look like;

df <- structure(list(ID = c(1L, 2L, 3L), A = structure(list(
    5, c(0.5, 0.6), 2), names = c("", "", "")), B = structure(list(
    c(0.2, 0.3), 6, c(0.1, 0.1)), names = c("", "", ""))), row.names = c(NA, 
3L), class = "data.frame")

I would like to mutate this to add the columns;

ID A B min_A max_A min_B max_B
1 5 0.2, 0.3 5 5 0.2 0.3
2 0.5, 0.6 6 0.5 0.6 6 6
3 2 0.1, 0.1 2 2 0.1 0.1

I have tried mutate(min_A = min(unlist(A))), but this seems to take the minimum value of the entire column of A rather than just the list on any given row. mutate(min_A = min(A)) errors out because list is an invalid argument type for the min command. So how might I go about adding the data I'm after?

推荐答案

Using map with across

library(purrr)
library(dplyr)
df %>% 
 mutate(across(A:B,  ~map_dbl(.x, min), .names = 'min_{.col}'),
       across(A:B, ~ map_dbl(.x, max), .names = 'max_{.col}'))

-output

 ID        A        B min_A min_B max_A max_B
1  1        5 0.2, 0.3   5.0   0.2   5.0   0.3
2  2 0.5, 0.6        6   0.5   6.0   0.6   6.0
3  3        2 0.1, 0.1   2.0   0.1   2.0   0.1

R相关问答推荐

如何将旋转后的NetCDF转换回正常的纬度/经度网格,并使用R?

IMF IFS数据以R表示

在ggplot2中更改小提琴情节的顺序

基于Key->Value数据帧的基因子集相关性提取

正在导出默认的RStudio主题,还是设置括号 colored颜色 ?

WRS2包中带有bwtrim的简单ANOVA抛出错误

防止正则表达式覆盖以前的语句

如何使投篮在R中保持一致

使用列名和r中的前缀 Select 列的CREATE函数

如何在矩阵图中按标准对数据进行分组以绘制矩阵

如何在R中的两列以上使用联合(&U)?

使用显式二元谓词子集化sfc对象时出错

为什么R列名称忽略具有指定名称的向量,而只关注索引?

使用点图调整离散轴比例

向内存不足的数据帧添加唯一行

根据列和行的不同组合 Select 各种单元格

通过判断行的值将数据从宽格式转换为长格式

如何在R中使用ggplot2将面图与面标签对齐

将来自具有特定条件的两个不同数据帧的列相乘

根据R中元素的索引,";CASE_WHEN&QOOT;?