r - 如何避免 R 中的循环?

标签 r loops apply

我知道在 R最好尽可能避免循环。在这方面,我想执行下面代码的功能,但不使用嵌套循环。
循环检查是否 f '向量的第 ' 个元素 things_I_want_to_find存在于 i '第 thing_to_be_searched 行.例如,当两个 if是1,代码检查是否"vocals"存在于 john的行。因为 "vocals"存在于 john的行,名称和乐器被添加到向量 instrumentname .当两个循环都完成时,这两个向量可以组合成 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/

相关文章:

r - 命令行 - 适用于 Windows 的 Awk 命令

r - 如何使用 R 自动重命名宽数据中的列

java - 在一周的时间跨度内每天按时间戳聚合对象

c++ - 为什么 cout 不起作用?

javascript - Google Chrome 上的结果不可预测

r - 如何对多列重复一个函数并将其组合在 data.frame 中并计算平均值?

r - 针织 latex forloop

r - 计算 data.frame 中的行和和乘积

python - 在 pandas 数据框上使用 apply 时传递值的形状错误

python - 使用 knit 编织时,无法在 RStudio 中使用网状导入 geopandas