ProgramingTip

일상 벡터에서 숫자 추출

bestdevel 2020. 10. 15. 08:07
반응형

일상 벡터에서 숫자 추출


다음과 같은 곳이 있습니다.

years<-c("20 years old", "1 years old")

이 벡터의 숫자 만 grep하고 싶습니다. 예상 출력은 벡터입니다.

c(20, 1)

어떻게해야합니까?


어때

# pattern is by finding a set of numbers in the start and capturing them
as.numeric(gsub("([0-9]+).*$", "\\1", years))

또는

# pattern is to just remove _years_old
as.numeric(gsub(" years old", "", years))

또는

# split by space, get the element in first index
as.numeric(sapply(strsplit(years, " "), "[[", 1))

나는 대체가 해결에서 간접적 인 방법이라고 생각합니다. 모든 번호를 검색하려는 gregexpr다음을 권장합니다 .

matches <- regmatches(years, gregexpr("[[:digit:]]+", years))
as.numeric(unlist(matches))

다중에 여러 개의 일치 항목이있는 경우 모두 가져옵니다. 첫 번째 일치에만 관심이있는 경우 regexpr대신 사용 gregexpr하고 unlist.


업데이트 이후 extract_numeric사용되지 않습니다,가 사용할 수 우리 있습니다 parse_number에서 readr패키지로 제공된다.

library(readr)
parse_number(years)

여기에 또 다른 옵션이 있습니다. extract_numeric

library(tidyr)
extract_numeric(years)
#[1] 20  1

다음은 더 간단한 Perl과 방법의 정규 사용하는 Arun의 첫 번째 솔루션에 대한 대안입니다.

as.numeric(gsub("[^\\d]+", "", years, perl=TRUE))

또는 간단히 :

as.numeric(gsub("\\D", "", years))
# [1] 20  1

stringr파이프 라인 솔루션 :

library(stringr)
years %>% str_match_all("[0-9]+") %>% unlist %>% as.numeric

모든 글자도 제거 할 수 있습니다.

as.numeric(gsub("[[:alpha:]]", "", years))

그러나 덜 일반화 될 수 있습니다.


시작 위치의 숫자에서 숫자를 추출합니다.

x <- gregexpr("^[0-9]+", years)  # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))

위치의 독립적 인 숫자에서 숫자를 추출합니다.

x <- gregexpr("[0-9]+", years)  # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))

에서 포스트 후 가보 르 그로 텐 디크의 는 R- 도움말 메일 링리스트에서 포스트

years<-c("20 years old", "1 years old")

library(gsubfn)
pat <- "[-+.e0-9]*\\d"
sapply(years, function(x) strapply(x, pat, as.numeric)[[1]])

우리는 또한 사용할 수 있습니다 str_extract.stringr

years<-c("20 years old", "1 years old")
as.integer(stringr::str_extract(years, "\\d+"))
#[1] 20  1

모든 숫자를 사용 str_extract_all하는 경우 에는 모든 마키를 사용 하는 방식을 사용할 수 있습니다 str_extract.

years<-c("20 years old and 21", "1 years old")
stringr::str_extract(years, "\\d+")
#[1] "20"  "1"

stringr::str_extract_all(years, "\\d+")

#[[1]]
#[1] "20" "21"

#[[2]]
#[1] "1"

참고 URL : https://stackoverflow.com/questions/14543627/extracting-numbers-from-vectors-of-strings

반응형