Wydobywanie ostatnich n znaków z ciągu znaków w R
Jak mogę pobrać Ostatnie n znaków z ciągu znaków w R? Czy istnieje taka funkcja jak SQL?
15 answers
Nie jestem świadomy niczego w bazie R, ale to proste, aby zrobić funkcję do tego za pomocą substr
i nchar
:
x <- "some text in a string"
substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}
substrRight(x, 6)
[1] "string"
substrRight(x, 8)
[1] "a string"
To jest wektoryzowane, jak wskazuje @mdsumner. Consider:
x <- c("some text in a string", "I really need to learn how to count")
substrRight(x, 6)
[1] "string" " count"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 12:30:25
Jeśli nie masz nic przeciwko użyciu pakietu stringr
, str_sub
jest przydatny, ponieważ możesz używać negatywów do liczenia wstecz:
x <- "some text in a string"
str_sub(x,-6,-1)
[1] "string"
Lub, jak Max wskazuje w komentarzu do tej odpowiedzi,
str_sub(x, start= -6)
[1] "string"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 08:37:20
Użyj funkcji stri_sub
z pakietu stringi
.
Aby uzyskać podłańcuch od końca, użyj liczb ujemnych.
Zobacz poniżej przykłady:
stri_sub("abcde",1,3)
[1] "abc"
stri_sub("abcde",1,1)
[1] "a"
stri_sub("abcde",-3,-1)
[1] "cde"
Możesz zainstalować ten pakiet z Githuba: https://github.com/Rexamine/stringi
Jest już dostępny na CRAN, po prostu wpisz
install.packages("stringi")
Aby zainstalować ten pakiet.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-13 13:38:51
str = 'This is an example'
n = 7
result = substr(str,(nchar(str)+1)-n,nchar(str))
print(result)
> [1] "example"
>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 16:30:00
Innym dość prostym sposobem jest użycie wyrażeń regularnych i sub
:
sub('.*(?=.$)', '', string, perl=T)
Więc, "pozbądź się wszystkiego, po którym następuje jeden znak". Aby pobrać więcej znaków z końca, dodaj jednak wiele kropek w twierdzeniu lookahead: {]}
sub('.*(?=.{2}$)', '', string, perl=T)
Gdzie .{2}
oznacza ..
, lub "dowolne dwa znaki", czyli"pozbądź się wszystkiego, po którym następuje dwa znaki".
sub('.*(?=.{3}$)', '', string, perl=T)
Dla trzech znaków itp. Możesz ustawić liczbę znaków do przechwycenia za pomocą zmiennej, ale będziesz należy paste
wartość zmiennej do ciągu wyrażenia regularnego:
n = 3
sub(paste('.+(?=.{', n, '})', sep=''), '', string, perl=T)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-11 05:04:08
UPDATE: Jak zauważył mdsumner , oryginalny kod jest już wektoryzowany, ponieważ substr jest. Trzeba było być ostrożniejszym.
I jeśli chcesz wersję wektorowaną (opartą na kodzie Andrie)
substrRight <- function(x, n){
sapply(x, function(xx)
substr(xx, (nchar(xx)-n+1), nchar(xx))
)
}
> substrRight(c("12345","ABCDE"),2)
12345 ABCDE
"45" "DE"
Zauważ, że zmieniłem (nchar(x)-n)
na (nchar(x)-n+1)
, aby uzyskać n
znaki.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:37
Proste rozwiązanie bazowe R przy użyciu funkcji substring()
(Kto by pomyślał, że ta funkcja w ogóle istnieje?):
RIGHT = function(x,n){
substring(x,nchar(x)-n+1)
}
To korzysta z tego, że zasadniczo jest substr()
pod spodem, ale ma domyślną wartość końcową 1,000,000.
Przykłady:
> RIGHT('Hello World!',2)
[1] "d!"
> RIGHT('Hello World!',8)
[1] "o World!"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-04 11:24:44
Alternatywą dla {[1] } jest podzielenie ciągu znaków na listę pojedynczych znaków i proces, który:
N <- 2
sapply(strsplit(x, ""), function(x, n) paste(tail(x, n), collapse = ""), N)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 08:30:22
Ja też używam substr
, ale w inny sposób. Chcę wyodrębnić Ostatnie 6 znaków "Daj mi swoje jedzenie."Oto kroki:
(1) Podziel znaki
splits <- strsplit("Give me your food.", split = "")
(2) Wyodrębnij Ostatnie 6 znaków
tail(splits[[1]], n=6)
Wyjście:
[1] " " "f" "o" "o" "d" "."
Każdy znak może być dostępny przez splits[[1]][x]
, gdzie x wynosi od 1 do 6.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-25 18:24:36
Spróbuj tego:
x <- "some text in a string"
n <- 5
substr(x, nchar(x)-n, nchar(x))
Powinno dać:
[1] "string"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-10 19:27:24
Ktoś wcześniej używa podobnego rozwiązania do mojego, ale mi łatwiej jest myśleć jak poniżej:
> text<-"some text in a string" # we want to have only the last word "string" with 6 letter
> n<-5 #as the last character will be counted with nchar(), here we discount 1
> substr(x=text,start=nchar(text)-n,stop=nchar(text))
Spowoduje to wyświetlenie ostatnich znaków zgodnie z życzeniem.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-05 18:22:19
Użyłem poniższego kodu, aby uzyskać ostatni znak łańcucha.
substr(output, nchar(stringOfInterest), nchar(stringOfInterest))
Możesz grać za pomocą nchar (stringOfInterest), aby dowiedzieć się, jak zdobyć kilka ostatnich znaków.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-24 23:42:20
NapisaĹ ' em kilka funkcji, ktĂłre mogÄ ... wykonaÄ ‡ wszystkie te funkcje po oblaniu ostatniego egzaminu z manipulacji strunami w programowaniu R. Jeśli pochodzisz z Excela, funkcje te będą podobne do LEFT()
, RIGHT()
, i MID()
funkcje.
# This counts from the left and then extract n characters
str_left <- function(string, n) {
substr(string, 1, n)
}
# This counts from the right and then extract n characters
str_right <- function(string, n) {
substr(string, nchar(string) - (n - 1), nchar(string))
}
# This extract characters from the middle
str_mid <- function(string, from = 2, to = 5){
substr(string, from, to)
}
Przykłady:
x <- "some text in a string"
str_left(x, 4)
[1] "some"
str_right(x, 6)
[1] "string"
str_mid(x, 6, 9)
[1] "text"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-08-27 11:37:56
Mała modyfikacja na @ Andrie rozwiązanie daje również dopełnienie:
substrR <- function(x, n) {
if(n > 0) substr(x, (nchar(x)-n+1), nchar(x)) else substr(x, 1, (nchar(x)+n))
}
x <- "moSvmC20F.5.rda"
substrR(x,-4)
[1] "moSvmC20F.5"
Tego właśnie szukałem. I zaprasza na lewą stronę:
substrL <- function(x, n){
if(n > 0) substr(x, 1, n) else substr(x, -n+1, nchar(x))
}
substrL(substrR(x,-4),-2)
[1] "SvmC20F.5"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-21 19:15:26
Na wypadek, gdyby trzeba było wybrać zakres znaków:
# For example, to get the date part from the string
substrRightRange <- function(x, m, n){substr(x, nchar(x)-m+1, nchar(x)-m+n)}
value <- "REGNDATE:20170526RN"
substrRightRange(value, 10, 8)
[1] "20170526"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-02 00:20:57