【发布时间】:2014-06-30 05:15:33
【问题描述】:
我在r中定义了如下函数:
#A function that compares color and dates to determine if there is a match
getTagColor <- function(color, date){
for (i in (1:nrow(TwistTieFix))){
if ((color == TwistTieFix$color_match[i]) &
(date > TwistTieFix$color_match[i]) &
(date <= TwistTieFix$julian_cut_off_date[i])) {
Data$color_code <- TwistTieFix$color_code[i]
print(Data$color_code)
}
}
}
然后我使用 apply() 尝试将函数应用于每一行。
#Apply the above function to the data set
testData <- apply(Data, 1, getTagColor(Data$tag_color,Data$julian_date))`
代码的目标是使用 Data 中的两个变量,并根据 TwistTieFix 中的信息找到另一个值以放入 Data 中的新列 (color_code)。当我运行代码时,我得到一个警告列表,上面写着
In if ((color == TwistTieFix$color_match[i]) & (date > ... :
the condition has length > 1 and only the first element will be used
我无法确定为什么该函数不使用每一行的日期和颜色并将其用于函数中(至少我认为这是错误的)。谢谢!
以下是使用的数据框示例:
TwistTieFix
color_name date color_code cut_off_date color_match julian_start julian_cut_off_date
yellow 2013-08-12 y1 2001-07-02 yellow 75 389
blue 2000-09-28 b1 2001-08-12 blue 112 430
数据
coll_date julian_date tag_color
2013-08-13 76 yellow
2013-08-14 76 yellow
2000-09-29 112 blue
数据有更多不同变量的列,但我不允许包含所有列。但是,我在函数中引用了 Data 中的列。数据集使用 read.csv 加载到 r 中,并且来自 Excel csv 文件。
【问题讨论】:
-
你能发布一个可重现的例子吗?请注意,apply 会将行(或列)作为第一个参数传递给函数,额外的参数应该作为额外的参数传递给 apply。
-
示例输入和所需输出在这里会非常有帮助。有关如何做到这一点的提示,请参阅how to make a great R reproducible example。您真的不需要在 data.frame
. Most operations are vectorized or can be vectorized so that you can just pass in the columns. Certainly there is a better way to write thegetTagColor` 函数的行上使用apply,但是如果没有看到TwistTieFix或您的输入数据,很难提供具体建议。 -
在函数内部调用对象 (
TwistTieFix) 而不将其作为参数传递是一个非常糟糕的主意。父母环境中迟早会发生让你伤心的事情。
标签: r user-defined-functions apply