【发布时间】:2018-08-29 04:30:25
【问题描述】:
我正在尝试创建一个基于多个条件对数据进行分箱的函数。我的数据有两个变量:max_dist 和 activated.
该函数应该为不同的 bin 创建多个向量;检查max_dist 是否在特定范围内,然后将1 附加到向量,如果它在范围内,activated 是TRUE,如果activated 是@987654332,则将0 附加到列表中@。
关键部分是,对于每个观察,如果 max_dist 大于指定范围但activated 也是TRUE,那么我想在那个 bin 中包含一个 0。所以一些观察值高 @987654335 @ 值将被分箱多次。
目前我的结构是这样的(缩短版 - 全长有 6 个箱子):
binning_function <- function(df) {
#create a series of vectors corresponding to bins
two_hundred <- c()
four_hundred <- c()
#iterate through dataframe to add 0 or 1 values to each vector
for (i in 1:nrow(df)) {
if (df$activated[i]==TRUE && df$max_dist[i]<=0.2) {
append(two_hundred, 1)
}
else if (df$max_dist[i]>0.2 || df$activated[i]==FALSE) {
append(two_hundred, 0)
}
}
for (i in 1:nrow(df)) {
if (df$activated[i]==TRUE && df$max_dist[i]>0.2 && df$max_dist[i]<=0.4) {
append(four_hundred, 1)
}
else if (df$max_dist[i]>0.4 || df$activated[i]==FALSE) {
append(four_hundred, 0)
}
}
return(list(two_hundred,four_hundred))
}
当我在数据帧上运行此函数时,它会返回一个列表:
[[1]]
NULL
[[2]]
NULL
【问题讨论】:
-
EJBailey,请尝试打开一个全新的 R 会话(例如我这里的),加载此代码,然后意识到没有可工作的数据。除了一些示例数据(请阅读下面的链接),它还有助于了解给定数据的预期输出。好的参考:stackoverflow.com/questions/5963269、stackoverflow.com/help/mcve 和 stackoverflow.com/tags/r/info。
-
感谢 r2evans,及时注明。
标签: r function for-loop rstudio binning