我知道在 R
最好尽可能避免循环。在这方面,我想执行下面代码的功能,但不使用嵌套循环。
循环检查是否 f
'向量的第 ' 个元素 things_I_want_to_find
存在于 i
'第 thing_to_be_searched
行.例如,当两个 i
和 f
是1,代码检查是否"vocals"
存在于 john
的行。因为 "vocals"
存在于 john
的行,名称和乐器被添加到向量 instrument
和 name
.当两个循环都完成时,这两个向量可以组合成 data.frame
.
我知道有 apply()
R 中的函数系列,但我不知道在这种情况下是否可以使用它们。有没有人有任何有用的提示或建议?
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 - 如何避免 R 中的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67637297/