在R列中分割字符串并获取分割字符串的最大值

时间:2020-04-06 20:47:13

标签: r

我有一个数据框,该数据框的一列中的数字包含在字符串中

例如

test<-data.frame(a=c('"1;2;3;4"','".;.;."',NA,'"5;.;7;8"'))

我想创建第二个列,该列要么是拆分字符串的最大值,要么是NA(如果不可用)。

我尝试过:

test$b<- ifelse(!is.na(test$a),as.numeric(max(strsplit(test$a, ";"))),NA)

但是会引发错误。

所以test $ b应该等于4,NA,NA,8

预先感谢您的帮助

4 个答案:

答案 0 :(得分:3)

这里是一个选项,其中我们将'a'列除以非数字字符,然后以条件list if遍历all,返回值NA { 1}},否则将获得NA个值中的max

numeric

答案 1 :(得分:2)

另一个基本的R解决方案可能正在使用regmatches + sapply,例如

test <- within(test,b <- sapply(regmatches(a,gregexpr("\\d+",a)),
                                function(x) ifelse(length(x),max(as.numeric(x)),NA)))

这样

> test
          a  b
1 "1;2;3;4"  4
2   ".;.;." NA
3      <NA> NA
4 "5;.;7;8"  8

答案 2 :(得分:2)

[[:punct:]]将过滤掉! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ {| }〜.`

有关更多信息,请阅读:?regex

test$b <- unlist(lapply(strsplit(test$a, "[[:punct:]]"), function(x) {
  x <- as.numeric(x)
  ifelse(all(is.na(x)), NA, max(x, na.rm = TRUE))
} ))
test
#           a  b
# 1 "1;2;3;4"  4
# 2   ".;.;." NA
# 3      <NA> NA
# 4 "5;.;7;8"  8

答案 3 :(得分:1)

使用data.table包:

# set up:
library(data.table)
setDT(test)

# solution:
test[, b := as.numeric(sapply(strsplit(gsub('"', "", a), ";"), max)), by = 1:4]