Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First entry from string split

Tags:

split

r

I've got a column people$food that has entries like chocolate or apple-orange-strawberry.

I want to split people$food by - and get the first entry from the split.

In python, the solution would be food.split('-')[0], but I can't find an equivalent for R.

like image 873
Pistol Pete Avatar asked Nov 13 '15 00:11

Pistol Pete


People also ask

How do you get your first element after a split?

To split a string and get the first element of the array, call the split() method on the string, passing it the separator as a parameter, and access the array element at index 0 . For example, str. split(',')[0] splits the string on each comma and returns the first array element.

How do you split a string on first occurrence?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you split the first part of a string in Python?

Use the str. split() method with maxsplit set to 1 to split a string and get the first element, e.g. my_str. split('_', 1)[0] .

How do I get the first element of a string in R?

We can get the first character of a string by using the built-in substr() function in R. The substr() function takes 3 arguments, the first one is a string, the second is start position, third is end position.


1 Answers

If you need to extract the first (or nth) entry from each split, use:

word <- c('apple-orange-strawberry','chocolate')  sapply(strsplit(word,"-"), `[`, 1) #[1] "apple"     "chocolate" 

Or faster and more explictly:

vapply(strsplit(word,"-"), `[`, 1, FUN.VALUE=character(1)) #[1] "apple"     "chocolate" 

Both bits of code will cope well with selecting whichever value in the split list, and will deal with cases that are outside the range:

vapply(strsplit(word,"-"), `[`, 2, FUN.VALUE=character(1)) #[1] "orange" NA   
like image 196
thelatemail Avatar answered Oct 19 '22 05:10

thelatemail