使用 Apply 函数而不是 for 循环
Using Apply functions instead of for loops
我有一个包含 59 列的数据集
第 4 到 59 列混合了电子邮件地址和废话
我想创建一个向量(最终将进入数据框),从 4:59 列中获取唯一的电子邮件地址。下面是我的函数,它对一列 EMAIL0 非常有效。这些列是连续的,因此 EMAIL0-EMAIL55
udf.Unique.Emails <- function (strcol, data)
{
vector <- as.character()
# For All columns with an email in the data set
for(i in 1:length(data))
{
# Check All the items in the row per email
if (grepl("@", strcol[i]))
{
vector <- unique(c(vector,strcol[i]))
}
}
return (vector)
}
test <- udf.Unique.Emails (foo$EMAIL0, foo.data)
我希望在 4:59 的所有列上实施此操作以生成单个列,任何人都可以使用 apply 系列为我指明正确的方向吗?
感谢您的宝贵时间
#######更新#####
由于问题中数据的敏感性,我不能提供太多细节。下面是一个模型,其中数据被称为 foo.data 并且数据和列被送入函数
对于 EMAIL0,函数
将返回 foo@fpo.com
最终结果将是一个单独的列,其中包含来自下方所有其他电子邮件列的所有唯一电子邮件
$ EMAIL0 (chr) "foo@fpo.com", "Recieved Report", "Daily", "Query", "Weekly", "Products", "Products2", "Results", "Products...
$ EMAIL1 (chr) "foo2@fpo2.com", "", "Nonsense", "", "", "garbage", "", "", "Trace Stack", "", "", "", "", "", "", "JS@fpo.com", "", "",...
$ EMAIL2 (chr) "John.Smith@fpo.com", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "John.Smith.Weston@fpo.com"
你可以试试:
data[which(matrix(grepl("@",as.matrix(data)),ncol=55),arr.ind=T)]
它基本上会得到有“@”的索引和returns这些索引处的值。
类似于
我有一个包含 59 列的数据集 第 4 到 59 列混合了电子邮件地址和废话 我想创建一个向量(最终将进入数据框),从 4:59 列中获取唯一的电子邮件地址。下面是我的函数,它对一列 EMAIL0 非常有效。这些列是连续的,因此 EMAIL0-EMAIL55
udf.Unique.Emails <- function (strcol, data)
{
vector <- as.character()
# For All columns with an email in the data set
for(i in 1:length(data))
{
# Check All the items in the row per email
if (grepl("@", strcol[i]))
{
vector <- unique(c(vector,strcol[i]))
}
}
return (vector)
}
test <- udf.Unique.Emails (foo$EMAIL0, foo.data)
我希望在 4:59 的所有列上实施此操作以生成单个列,任何人都可以使用 apply 系列为我指明正确的方向吗?
感谢您的宝贵时间
#######更新#####
由于问题中数据的敏感性,我不能提供太多细节。下面是一个模型,其中数据被称为 foo.data 并且数据和列被送入函数
对于 EMAIL0,函数
将返回 foo@fpo.com最终结果将是一个单独的列,其中包含来自下方所有其他电子邮件列的所有唯一电子邮件
$ EMAIL0 (chr) "foo@fpo.com", "Recieved Report", "Daily", "Query", "Weekly", "Products", "Products2", "Results", "Products...
$ EMAIL1 (chr) "foo2@fpo2.com", "", "Nonsense", "", "", "garbage", "", "", "Trace Stack", "", "", "", "", "", "", "JS@fpo.com", "", "",...
$ EMAIL2 (chr) "John.Smith@fpo.com", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "John.Smith.Weston@fpo.com"
你可以试试:
data[which(matrix(grepl("@",as.matrix(data)),ncol=55),arr.ind=T)]
它基本上会得到有“@”的索引和returns这些索引处的值。
类似于