如何避免R中出现循环? [英] How do I avoid loops in R?
问题描述
我了解在 R
中,最好尽可能避免循环.在这方面,我想执行以下代码的功能,但不使用嵌套循环.
I understand that in R
it is best to avoid loops where possible. In that regard, I would like to perform the function of the code below but without using the nested loops.
循环检查向量 things_I_want_to_find
的第 f
个元素是否存在于 thing_to_be_searched的第
.例如,当 i
个行中 i
和 f
均为1时,代码检查 john
"vocals" >的行.因为 vocals"
is 出现在 john
的行中,名称和乐器被添加到向量 instrument
和 name
.当两个循环都完成时,可以将这两个向量合并到 data.frame
中.
The loops check whether the f
'th element of the vector things_I_want_to_find
is present in the i
'th row of thing_to_be_searched
. For example, when both i
and f
are 1, the code checks whether "vocals"
is present in john
's row. Because "vocals"
is present in john
's row, the name and instrument are added to vectors instrument
and name
. When both loops are complete these two vectors can be combined in a data.frame
.
我知道R中有 apply()
函数族,但是我不知道在这种情况下是否可以使用它们.有没有人有任何有用的提示或建议?
I know that there is the apply()
family of functions in R but I don't know if they are able to be used in this case. Has anyone got any helpful hints or suggestions?
instrument<-c()
name<-c()
things_I_want_to_find<-c("vocals","drums","rhythm guitar","bass")
thing_to_be_searched<-
data.frame(
id=c("john","paul","george","ringo"),
a=c("vocals","bass","rhythm guitar","oboe"),
b=c("vocals","basoon","piano","clarinet"),
c=c("violin","vocals","french horn","drums"))
for(f in 1:length(things_I_want_to_find))
{
for(i in 1:nrow(thing_to_be_searched))
{
n<-which(thing_to_be_searched[i,]==things_I_want_to_find[f])
if(length(n)>0)
{
instrument<-c(instrument,as.character(thing_to_be_searched[i,][n][,1][1]))
name<-c(name,as.character(thing_to_be_searched$id[i]))
}
}
}
desired_output<-data.frame(name=name,instrument=instrument)
desired_output
name instrument
1 john vocals
2 paul vocals
3 ringo drums
4 george rhythm guitar
5 paul bass
推荐答案
library(tidyverse)
thing_to_be_searched %>%
# Melt wide data to long
pivot_longer(-1) %>%
# Drop unwanted column
select(-name) %>%
# Filter wanted values only
filter( value %in% things_I_want_to_find) %>%
# Only keep unique rows
unique()
输出
# A tibble: 5 x 2
id value
<chr> <chr>
1 john vocals
2 paul bass
3 paul vocals
4 george rhythm guitar
5 ringo drums
这篇关于如何避免R中出现循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!