Using selected vector element as an operator - r

If I define a vector as:
vec <- c("for", "paste")
Is there any way to apply a selection on this vector and use the result as an operator? I have tried like this:
vec[1](i, 0:10, print("Hello"))
but the result is an error:
Error: attempt to apply non-function

The first element in 'vec' i.e. for is a Primitive function, so, we can append .Primitive
.Primitive(vec[1])(i, 0:10, print("Hello"))
-output
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
while paste is not Primitive. Not clear from the OP's post about the expected output for second element. With match.fun, we can use
match.fun(vec[2])(rep("Hello", 10), collapse=", ")
#[1] "Hello, Hello, Hello, Hello, Hello, Hello, Hello, Hello, Hello, Hello"
assuming that OP' wants to paste 10 "Hello" into a single string

How about?
vec <- c("for", "paste")
do.call(vec[[1]], list(as.symbol('i'), 0:10, substitute(print('Hello'))))

Related

Selectively removing trailing string

I want to remove the last letter "O", except where is is part of the word "HELLO".
I've tried doing this:
Example:
a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)
[1] "HELLO " " HELLO" "T " "HO"
but I want
"HELLO X" "D HELLO" "TW X" "H"
Try replacing using the following pattern:
\b(?!HELLO\b)(\w+)O\b
This says to assert that the word HELLO does not appear as the word, and then captures everything up until the final O, should it occur. Then, it replaces with that optional final O removed.
\b - from the start of the word
(?!HELLO\b) - assert that the word is not HELLO
(\w+)O - match a word ending in O, but don't capture final O
\b - end of word
The capture group, if a match happens, will contain the entire word minus the final O.
Code:
a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("\\b(?!HELLO\\b)(\\w+)O\\b", "\\1", a, perl=TRUE)
[1] "HELLO X" "D HELLO" "TW X" "H"
Note that we must Perl mode enabled (perl=TRUE) with gsub in order to use the negative lookahead.
Demo
Use regex alternation operator |
a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("(HELLO)|O(?!\\S)", "\\1", a, perl=T)
# [1] "HELLO X" "D HELLO" "TW X" "H"
(HELLO)|O this regex does two things,
First it captures all the HELLO string.
Matches all the remaining 0's which are not followed by a non-space character.
Your regular expression is nit correct.[^HELLO] means any character except H, E, L and O. But you need except only exactly HELL before O. So, you should use following expression:
a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("(?<!\\bHELL)O\\b", "", a, perl=TRUE)
a <- c("HELLO XO","DO HELLO","TWO XO","HO")
aa <- gsub("O","",a)
gsub("HELL", "HELLO",aa)
A little lengthy, but you can try like this
a <- c("HELLO XO","DO HELLO","TWO XO","HO")
b <- lapply(a, function(x) unlist(strsplit(x, " ")))
b
> b
[[1]]
[1] "HELLO" "XO"
[[2]]
[1] "DO" "HELLO"
[[3]]
[1] "TWO" "XO"
[[4]]
[1] "HO"
c <- unlist(lapply(b, function(y) paste(ifelse( y == "HELLO", "HELLO", gsub("O", "", y)), collapse = " " )))
c
[1] "HELLO X" "D HELLO" "TW X" "H"

Accessing element of a split string in R

If I have a string,
x <- "Hello World"
How can I access the second word, "World", using string split, after
x <- strsplit(x, " ")
x[[2]] does not do anything.
As mentioned in the comments, it's important to realise that strsplit returns a list object. Since your example is only splitting a single item (a vector of length 1) your list is length 1. I'll explain with a slightly different example, inputting a vector of length 3 (3 text items to split):
input <- c( "Hello world", "Hi there", "Back at ya" )
x <- strsplit( input, " " )
> x
[[1]]
[1] "Hello" "world"
[[2]]
[1] "Hi" "there"
[[3]]
[1] "Back" "at" "ya"
Notice that the returned list has 3 elements, one for each element of the input vector. Each of those list elements is split as per the strsplit call. So we can recall any of these list elements using [[ (this is what your x[[2]] call was doing, but you only had one list element, which is why you couldn't get anything in return):
> x[[1]]
[1] "Hello" "world"
> x[[3]]
[1] "Back" "at" "ya"
Now we can get the second part of any of those list elements by appending a [ call:
> x[[1]][2]
[1] "world"
> x[[3]][2]
[1] "at"
This will return the second item from each list element (note that the "Back at ya" input has returned "at" in this case). You can do this for all items at once using something from the apply family. sapply will return a vector, which will probably be good in this case:
> sapply( x, "[", 2 )
[1] "world" "there" "at"
The last value in the input here (2) is passed to the [ operator, meaning the operation x[2] is applied to every list element.
If instead of the second item, you'd like the last item of each list element, we can use tail within the sapply call instead of [:
> sapply( x, tail, 1 )
[1] "world" "there" "ya"
This time, we've applied tail( x, 1 ) to every list element, giving us the last item.
As a preference, my favourite way to apply actions like these is with the magrittr pipe, for the second word like so:
x <- input %>%
strsplit( " " ) %>%
sapply( "[", 2 )
> x
[1] "world" "there" "at"
Or for the last word:
x <- input %>%
strsplit( " " ) %>%
sapply( tail, 1 )
> x
[1] "world" "there" "ya"
Another approach that might be a little easier to read and apply to a data frame within a pipeline (though it takes more lines) would be to wrap it in your own function and apply that.
library(tidyverse)
df <- data.frame(
greetings = c( "Hello world", "Hi there", "Back at ya" )
)
split_params = function (x, sep, n) {
# Splits string into list of substrings separated by 'sep'.
# Returns nth substring.
x = strsplit(x, sep)[[1]][n]
return(x)
}
df = df %>%
mutate(
'greetings' = sapply(
X = greetings,
FUN = split_params,
# Arguments for split_params.
sep = ' ',
n = 2
)
)
df
### (Output in RStudio Notebook)
greetings second_word
<chr> <chr>
Hello world world
Hi there there
Back at ya at
3 rows
###
With stringr 1.5.0, you can use str_split_i to access the ith element of a split string:
library(stringr)
x <- "Hello World"
str_split_i(x, " ", i = 2)
#[1] "World"
It is vectorized:
x <- c("Hello world", "Hi there", "Back at ya")
str_split_i(x, " ", 2)
#[1] "world" "there" "at"
x=strsplit("a;b;c;d",";")
x
[[1]]
[1] "a" "b" "c" "d"
x=as.character(x[[1]])
x
[1] "a" "b" "c" "d"
x=strsplit(x," ")
x
[[1]]
[1] "a"
[[2]]
[1] "b"
[[3]]
[1] "c"
[[4]]
[1] "d"

Splitting a string in R

Consider:
x<-strsplit("This is an example",split="\\s",fixed=FALSE)
I am surprised to see that x has length 1 rather than length 4:
> length(x)
[1] 1
like this, x[3] is null. But If I unlist, then:
> x<-unlist(x)
> x
[1] "This" "is" "an" "example"
> length(x)
[1] 4
only now x[3] is "an".
Why wasn't that list originally by length 4 so that elements can be accessed by indexing? This gives troubles to access the splitted elements, since I have to unlist first.
This allows strsplit to be vectorized for its input argument. For instance, it will allow you to split a vector such as:
x <- c("string one", "string two", "and string three")
into a list of split results.
You do not need to unlist, but rather, you can refer to the element by a combination of its list index and the vector index. For instance, if you wanted to get the second word in the second item, you can do:
> x <- c("string one", "string two", "and string three")
> y <- strsplit(x, "\\s")
> y[[2]][2]
[1] "two"
That's because strsplit generates a list containing each element (word).
Try
> x[[1]]
#[1] "This" "is" "an" "example"
and
> length(x[[1]])
#[1] 4

R: cut string of characters in vectors

let x be the vector
[1] "hi" "hello" "Nyarlathotep"
Is it possible to produce a vector, let us say y, from x s.t. its components are
[1] "hi" "hello" "Nyarl"
?
In other words, I would need a command in R which cuts strings of text to a given length (in the above, length=5).
Thanks a lot!
More obvious than substring to me would be strtrim:
> x <- c("hi", "hello", "Nyarlathotep")
> x
[1] "hi" "hello" "Nyarlathotep"
> strtrim(x, 5)
[1] "hi" "hello" "Nyarl"
substring is great for extracting data from within a string at a given position, but strtrim does exactly what you're looking for.
The second argument is widths and that can be a vector of widths the same length as the input vector, in which case, each element can be trimmed by a specified amount.
> strtrim(x, c(1, 2, 3))
[1] "h" "he" "Nya"
Use substring see details in ?substring
> x <- c("hi", "hello", "Nyarlathotep")
> substring(x, first=1, last=5)
[1] "hi" "hello" "Nyarl"
Last update
You can also use sub with regex
> sub("(.{5}).*", "\\1", x)
[1] "hi" "hello" "Nyarl"
A (probably) faster alternative is sprintf():
sprintf("%.*s", 5, x)
[1] "hi" "hello" "Nyarl"

How should I split and retain elements using strsplit?

What a strsplit function in R does is, match and delete a given regular expression to split the rest of the string into vectors.
>strsplit("abc123def", "[0-9]+")
[[1]]
[1] "abc" "" "" "def"
But how should I split the string the same way using regular expression, but also retain the matches? I need something like the following.
>FUNCTION("abc123def", "[0-9]+")
[[1]]
[1] "abc" "123" "def"
Using strapply("abc123def", "[0-9]+|[a-z]+") works here, but what if the rest of the string other than the matches cannot be captured by a regular expression?
Fundamentally, it seems to me that what you want is not to split on [0-9]+ but to split on the transition between [0-9]+ and everything else. In your string, that transition is not pre-existing. To insert it, you could pre-process with gsub and back-referencing:
test <- "abc123def"
strsplit( gsub("([0-9]+)","~\\1~",test), "~" )
[[1]]
[1] "abc" "123" "def"
You could use lookaround assertions.
> test <- "abc123def"
> strsplit(test, "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)", perl=T)
[[1]]
[1] "abc" "123" "def"
You can use strapply from gsubfn package.
test <- "abc123def"
strapply(X=test,
pattern="([^[:digit:]]*)(\\d+)(.+)",
FUN=c,
simplify=FALSE)
[[1]]
[1] "abc" "123" "def"

Resources