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.
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.
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.
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] .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With