r - 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(),但没有运气。
解决方案
这是一个额外的答案,将其压缩一些并取消 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) ]
推荐阅读
- python - 将所有库和依赖项添加到 AWS lambda for python 应用程序
- php - Laravel 使用错误的表进行注册并返回“SQLSTATE[42S22]: Column not found”
- powershell - Invoke-Command 仅在数组中的最后一个节点上运行
- header-files - IAR Workbench 的头文件
- r - 在R中用ggplot2区分多个图例的位置
- mongodb - Why does my MongoDB data disappear when I convert my Meteor App to use Docker?
- react-native - React Native 椭圆滚动
- excel - 复制并粘贴到下一个空白行?
- dataframe - 将csv文件读入python pandas
- saml-2.0 - 对于某些 Idp,只有 Acs URL 发送 500 错误,不幸的是,没有记录或返回任何内容,以便了解究竟发生了什么