我有一个包含两个变量的数据框:分类和电子邮件ID。数据框的可重现的例子如下:
structure(list(Classification = structure(c(1L, 1L, 1L), .Label = "bills", class = "factor"),
FromMailId = structure(c(1L, 1L, 1L), .Label = "bimbilikkibimbi@yahoo.com", class = "factor")), .Names = c("Classification",
"FromMailId"), row.names = c(NA, 3L), class = "data.frame")
我正在使用库(mailR)发送邮件。我必须根据Classification变量中的值自定义邮件传递。我试图循环数据框以根据分类的值来获取电子邮件ID。以下是我正在使用的代码:
for(i in df1$Classification){
if(i == "bills"){
library(mailR)
send.mail(from = "UserName@gmail.com",
to = df1$FromMailId[i],
subject = paste("Subject: ", "This is a test message"),
body = "You have got bills",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "UserName", passwd = "PassWord", ssl = TRUE),
authenticate = TRUE,
send = TRUE)
}
}
如果我将'to'电子邮件ID更改为实际的电子邮件ID,则上述代码可以正常运行。但是当我将相同的字段引用到数据框中的列(此处为FromMailId)时,我收到以下错误:
Error in ls(envir = envir, all.names = private) :
invalid 'envir' argument
我收集说我正在引用循环中的特定列并引用send.mail中的另一列...但不知道如何解决此问题。
答案 0 :(得分:0)
您循环遍历Classification
的元素并尝试将其用作子集索引,这将无效。试试这个:
library(mailR) #No need to have that in the loop
for(i in 1:nrow(df1)){
if(df1$Classification[i] == "bills"){
send.mail(from = "UserName@gmail.com",
to = df1$FromMailId[i],
subject = paste("Subject: ", "This is a test message"),
body = "You have got bills",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "UserName", passwd = "PassWord", ssl = TRUE),
authenticate = TRUE,
send = TRUE)
}
}
答案 1 :(得分:-1)
我认为df1$FromMailId
是一个因素。所以尝试将其转换为角色。
使用df1$FromMailId <- as.character(df1$FromMailId, stringAsFactors = F)
转换列,或者只编辑to = as.character(df1$FromMailId[i])
的sendmail代码。