本文介绍了如何避免 R 中的循环:从列表中选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用循环来解决这个问题,但我尝试在向量中思考,因此我的代码将更具 R 风格.
I could solve this using loops, but I am trying think in vectors so my code will be more R-esque.
我有一个名字列表.格式为名字_姓氏.我想从这个列表中删除一个只有名字的单独列表.我似乎无法理解如何做到这一点.以下是一些示例数据:
I have a list of names. The format is firstname_lastname. I want to get out of this list a separate list with only the first names. I can't seem to get my mind around how to do this. Here's some example data:
t <- c("bob_smith","mary_jane","jose_chung","michael_marx","charlie_ivan")
tsplit <- strsplit(t,"_")
看起来像这样:
> tsplit
[[1]]
[1] "bob" "smith"
[[2]]
[1] "mary" "jane"
[[3]]
[1] "jose" "chung"
[[4]]
[1] "michael" "marx"
[[5]]
[1] "charlie" "ivan"
我可以使用这样的循环得到我想要的:
I could get out what I want using loops like this:
for (i in 1:length(tsplit)){
if (i==1) {t_out <- tsplit[[i]][1]} else{t_out <- append(t_out, tsplit[[i]][1])}
}
这会给我这个:
t_out
[1] "bob" "mary" "jose" "michael" "charlie"
那么我如何在没有循环的情况下做到这一点?
So how can I do this without loops?
推荐答案
您可以使用apply
(或sapply
)
t <- c("bob_smith","mary_jane","jose_chung","michael_marx","charlie_ivan")
f <- function(s) strsplit(s, "_")[[1]][1]
sapply(t, f)
bob_smith mary_jane jose_chung michael_marx charlie_ivan
"bob" "mary" "jose" "michael" "charlie"
参见:简要介绍在 R 中应用"
这篇关于如何避免 R 中的循环:从列表中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!