R:从列中的每个字符值中提取最高数值

Reb*_*ham 0 r

我在数据框中有一个包含数字的字符字段,例如(0.5,3.5,7.8,2.4).

对于每个记录,我试图从字符串中提取最大值并将其放入新列中.

例如

x  csi
1  0.5, 6.7, 2.3   
2  9.5, 2.6, 1.1
3  0.7, 2.3, 5.1
4  4.1, 2.7, 4.7
Run Code Online (Sandbox Code Playgroud)

期望的输出是:

x  csi            csi_max
1  0.5, 6.7, 2.3  6.7
2  9.5, 2.6, 1.1  9.5
3  0.7, 2.3, 5.1  5.1
4  4.1, 2.7, 4.7  4.7
Run Code Online (Sandbox Code Playgroud)

我有各种尝试......我的最新尝试是以下 - 它提供了整个列的最大csi分数,而不是单个行的csi数字...

library(stringr)
numextract <- function(string){ 
  str_extract(string, "\\-*\\d+\\.*\\d*")
} 
df$max_csi <- max(numextract(df$csi))
Run Code Online (Sandbox Code Playgroud)

谢谢

akr*_*run 6

我们可以用 tidyverse

library(dplyr)
library(tidyr)
df1  %>% 
    separate_rows(csi) %>%
    group_by(x) %>% 
    summarise(csi_max = max(csi)) %>%
    left_join(df1, .)
#  x           csi csi_max
#1 1 0.5, 6.7, 2.3     6.7
#2 2 9.5, 2.6, 1.1     9.5
#3 3 0.7, 2.3, 5.1     5.1
#4 4 4.1, 2.7, 4.7     4.7
Run Code Online (Sandbox Code Playgroud)

或者,这是可以做到pmaxbase R了"CSI"列分成后data.frameread.table

df1$csi_max <- do.call(pmax, read.table(text=df1$csi, sep=","))
Run Code Online (Sandbox Code Playgroud)