See .?substring
x <- 'hello stackoverflow'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello stackoverflow"
The idea of having a method that both returns a value and has a side effect of updating the data stored in pop is very much a concept from object-oriented programming. So rather than defining a x function to operate on character vectors, we can make a reference class with a pop method.pop
PopStringFactory <- setRefClass(
"PopString",
fields = list(
x = "character"
),
methods = list(
initialize = function(x)
{
x <<- x
},
pop = function(n = 1)
{
if(nchar(x) == 0)
{
warning("Nothing to pop.")
return("")
}
first <- substring(x, 1, n)
x <<- substring(x, n + 1)
first
}
)
)
x <- PopStringFactory$new("hello stackoverflow")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello stackoverflow"
replicate(nchar(x$x), x$pop())
## [1] "h" "e" "l" "l" "o" " " "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"
If we need to remove the first character, use , match one character (sub represents a single character), replace it with ..''
sub('.', '', listfruit)
#[1] "applea" "bananab" "ranggeo"
Or for the first and last character, match the character at the start of the string () or the end of the string (^.) and replace it with .$.''
gsub('^.|.$', '', listfruit)
#[1] "apple" "banana" "rangge"
We can also capture it as a group and replace with the backreference.
sub('^.(.*).$', '\\1', listfruit)
#[1] "apple" "banana" "rangge"
Another option is with substr
substr(listfruit, 2, nchar(listfruit)-1)
#[1] "apple" "banana" "rangge"
You can do it with function and simple regex. Here is the code:gsub
# Fake data frame
df <- data.frame(text_col = c("abcd", "abcde", "abcdef"))
df$text_col <- as.character(df$text_col)
# Replace first 3 chracters with empty string ""
df$text_col <- gsub("^.{0,3}", "", df$text_col)
We can use substring
tweetsdf$usertweet <- substring(tweetsdf$usertweet, 3)
Or use sub
sub("\\S+\\s+", "", tweetsdf$usertweet)
Set the field separator to the path separator and read everything except the stuff before the first slash into :$name
while IFS=/ read junk name
do
echo $name
done < directory_listing.txt