Ich möchte die ersten (oder letzten) n Zeichen einer Zeichenfolge extrahieren . Dies wäre das Äquivalent zu Excel LEFT()
und RIGHT()
. Ein kleines Beispiel:
# create a string
a <- paste('left', 'right', sep = '')
a
# [1] "leftright"
I would like to produce b
, a string which is equal to the first 4 letters of a
:
b
# [1] "left"
What should I do?
stringr
solution.The
stringr
package provides thestr_sub
function, which is a bit easier to use thansubstr
, especially if you want to extract right portions of your string :R> str_sub("leftright",1,4) [1] "left" R> str_sub("leftright",-5,-1) [1] "right"
quelle
R
:)stringr
will save you almost as much aggravation aslubridate
.You can easily obtain Right() and Left() functions starting from the Rbase package:
right function
right = function (string, char) { substr(string,nchar(string)-(char-1),nchar(string)) }
left function
left = function (string,char) { substr(string,1,char) }
you can use those two custom-functions exactly as left() and right() in excel. Hope you will find it useful
quelle
Make it simple and use R basic functions:
# To get the LEFT part: > substr(a, 1, 4) [1] "left" > # To get the MIDDLE part: > substr(a, 3, 7) [1] "ftrig" > # To get the RIGHT part: > substr(a, 5, 10) [1] "right"
The
substr()
function tells you where start and stopsubstr(x, start, stop)
quelle
If you are coming from Microsoft Excel, the following functions will be similar to
LEFT()
,RIGHT()
, andMID()
functions.# 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) }
Examples:
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"
quelle