首页 > 解决方案 > R循环中的两个变量

问题描述

我需要在命名列表上循环一个函数,list[i]作为一个参数,names(list)[i]另一个作为参数。

这是一些假代码:

#generate DF

employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))

df <- data.table(employee, salary, startdate)
df$'tags' <- NA

#Create named list

test <- list(
  'JMan' = 'Doe',
  'PMan' = 'Peter',
  'JMan' = 'Hope'

)

#Create function to populate df$tags with output

func <- function(pattern, name) {
  df[, tags := fcase(
    employee %like% regex(pattern), name,
    rep(TRUE, nrow(df)), as.character(df$tags)
  )
  ]
}
#test function

df <- func(as.character(test[1]), names(test)[1])

这一切都很好:

         employee salary  startdate tags
1:   John Doe  21000 2010-11-01 JMan
2: Peter Gynn  23400 2008-03-25 <NA>
3: Jolie Hope  26800 2007-03-14 <NA>

但是,当我尝试迭代它时:

for (i in test) {
  df <- func(as.character(test[i]), names(test)[i])
  
}

什么都没发生。

任何帮助将不胜感激。我尝试过使用 apply() 和 apply(),但没有运气。

标签: rdata.table

解决方案


这是一个额外的答案,将其压缩一些并取消 for 循环,只是为了提供更多想法。(注意你能保证每个员工只有一场比赛吗?)


df <- data.table(employee, salary, startdate)

func <- function(employee) {
    i <- sapply( unlist(test), grepl, x=employee[1] )
    if(!any(i))
        return(NA)
    names(test)[i]
}

df[, tags := func(employee) , by=1:nrow(df) ]


推荐阅读