根据列中的正则表达式语法,将变量添加到包含每行最大值的数据框

Add a variable to a data frame containing max value of each row depending on a regex syntax in the column

我有一个包含结果和日期的非常大的数据集。数据的一小部分(我有更多具有不同名称和行的列):

  result_1    date_1 result_2    date_2 result_3    date_3 result_4    date_4
1        1 12.8.2020        4 13.8.2020        2 15.8.2020        1 20.8.2020
2        3 15.8.2020        3 14.8.2020        5 17.8.2020        2 21.8.2020

我想为结果列添加最大列和最大名称列,具体取决于列名(我使用的是正则表达式,因为并非所有列都正确命名) 我尝试了几个选项,似乎有效的选项是在选择包含我选择的正则表达式的列时创建另一个数据框。 我尝试了类似于以下代码的操作:

data_max <- data %>% 
  select(matches("result_")) %>% 
  rowwise() %>% 
  mutate(max = max(.))

我的想法是然后将 max 列与原始数据连接起来并找到列名,但我确信有更好的方法来做到这一点,特别是因为我的数据包含其他列名(不同正则表达式),我也想按行最大化,并且在某些列中有大量的 na。

您可以 select 'result' 列并使用 max.col :

cols <- grep('result', names(df), value = TRUE)
df$max_column <- cols[max.col(df[cols], ties.method = 'first')]
df

#  result_1    date_1 result_2    date_2 result_3    date_3 result_4    date_4 max_column
#1        1 12.8.2020        4 13.8.2020        2 15.8.2020        1 20.8.2020   result_2
#2        3 15.8.2020        3 14.8.2020        5 17.8.2020        2 21.8.2020   result_3

这给出了 'result' 列每行中最大值的列名。

数据

df <- structure(list(result_1 = c(1L, 3L), date_1 = c("12.8.2020", 
"15.8.2020"), result_2 = 4:3, date_2 = c("13.8.2020", "14.8.2020"
), result_3 = c(2L, 5L), date_3 = c("15.8.2020", "17.8.2020"), 
    result_4 = 1:2, date_4 = c("20.8.2020", "21.8.2020")), 
class = "data.frame", row.names = c(NA, -2L))