本文介绍了字符串拆分的第一个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 people$food
列,其中包含诸如 chocolate
或 apple-orange-strawberry
之类的条目.
I've got a column people$food
that has entries like chocolate
or apple-orange-strawberry
.
我想通过 -
拆分 people$food
并从拆分中获取第一个条目.
I want to split people$food
by -
and get the first entry from the split.
在 python 中,解决方案是 food.split('-')[0]
,但我找不到 R 的等价物.
In python, the solution would be food.split('-')[0]
, but I can't find an equivalent for R.
推荐答案
如果您需要从每个拆分中提取第一个(或 nth
)个条目,请使用:
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"
或者更快更明确:
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
这篇关于字符串拆分的第一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!