1

I have a list of strings which look like that:

categories <- "|Music|Consumer Electronics|Mac|Software|"

However, I only want get the first string. In this case Music(without |). I tried:

sub(categories, pattern = " |", replacement = "")

However, that does not give me the desired result. Any recommendation how to correctly parse my string?

I appreciate your answer!

UPDATE

> dput(head(df))
structure(list(data.founded_at = c("01.06.2012", "26.10.2012", 
"01.04.2011", "01.01.2012", "10.10.2011", "01.01.2007"), data.category_list = c("|Entertainment|Politics|Social Media|News|", 
"|Publishing|Education|", "|Electronics|Guides|Coffee|Restaurants|Music|iPhone|Apps|Mobile|iOS|E-Commerce|", 
"|Software|", "|Software|", "|Curated Web|")), .Names = c("data.founded_at", 
"data.category_list"), row.names = c(NA, 6L), class = "data.frame")
1
  • 1
    Several problems: 1) Your arguments for sub are in the wrong order. 2) You need to escape | with pattern = "\\|" 3) sub will only replace characters, not split strings. Commented Aug 13, 2014 at 14:37

3 Answers 3

3

An alternative for this could be scan:

na.omit(scan(text = categories, sep = "|", what = "", na.strings = ""))[1]
# Read 6 items
# [1] "Music"
Sign up to request clarification or add additional context in comments.

Comments

1

Find a function that will tokenize a string at a particular character: strsplit would be my guess.

http://stat.ethz.ch/R-manual/R-devel/library/base/html/strsplit.html

Comments

1

Note that the parameter in split is a regexp, so using split="|" will not work (unless you specify fixed=TRUE, as suggested from joran -thanks- in the comments)

strsplit(categories,split="[|]")[[1]][2]

To apply this to the data frame you could do this:

sapply(df$data.category_list, function(x) strsplit(x,split="[|]")[[1]][2])

But this is faster (see the comments):

vapply(strsplit(df$data.category_list, "|", fixed = TRUE), `[`, character(1L), 2)

(thanks to Ananda Mahto)

7 Comments

And, if you use strsplit, which returns a list, you might want to call unlist on the expression @momobo provided. That will return a vector.
@momobo Thx for your answer! How to do that on a dataframe?
@AnandaMahto I have added my used dataframe in an update. I would appreciate an answer from you, that I will gladly mark as accepted!
also df$firstCat <- sapply(df$data.category_list, function(x){strsplit(x,split="[|]")[[1]][2]})
Ok. Yours is faster. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.