【发布时间】:2017-11-01 20:49:57
【问题描述】:
我有一个缺失值的数据框,我编写了一个函数来使用 R 3.3.2 进行填充
pkgs <- c("dplyr", "ggplot2", "tidyr", 'data.table', 'lazyeval')
lapply(pkgs, require, character.only = TRUE)
UID <- c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C')
Col1 <- c(1, 0, 0, 0, 1, 0, 0, 0)
df <- data.frame(UID, Col1)
Col1 填写函数:
AggregatedColumns <- function(DF, columnToUse, NewCol1) {
# Setting up column names to use
columnToUse <- deparse(substitute(columnToUse))
NewCol1 <- deparse(substitute(NewCol1))
# Creating new columns
DF[[NewCol1]] <- ifelse(DF[[columnToUse]] == 1, 1, NA)
DF <- DF %>% group_by_("UID") %>% sort(DF[[columnToUse]], decreasing = TRUE) %>% fill_(NewCol1)
DF <- DF %>% group_by_("UID") %>% sort(DF$columnToUse, decreasing = TRUE) %>% fill_(NewCol1, .direction = 'up')
DF[[NewCol1]] <- ifelse(is.na(DF[[NewCol1]]), 0, DF[[NewCol1]])
DF
}
我已经删除了这部分功能,因为这是减慢功能的部分。我对编写函数非常陌生,任何关于如何/是否可以加快速度的建议将不胜感激。我已将速度问题隔离到函数的 fill_ 部分。
我想要做的是将一个虚拟变量从 Col1 传递到 New_Column,然后将填充转发到其他相同的 ID。例如:
UID Col1
John Smith 1
John Smith 0
应该变成
UID Col1 New_Column
John Smith 1 1
John Smith 0 1
编辑功能 我编辑了函数以符合@HubertL 的建议。该功能仍然相当慢,但希望通过这些编辑,该示例是可重现的。
AggregatedColumns <- function(DF, columnToUse, NewCol1) {
# Setting up column names to use
columnToUse <- deparse(substitute(columnToUse))
NewCol1 <- deparse(substitute(NewCol1))
# Creating new columns
DF[[NewCol1]] <- ifelse(DF[[columnToUse]] == 1, 1, NA)
DF <- DF %>% group_by_("UID") %>% fill_(NewCol1) %>% fill_(NewCol1, .direction = 'up')
DF[[NewCol1]] <- ifelse(is.na(DF[[NewCol1]]), 0, DF[[NewCol1]])
DF
}
期望的输出:
UID Col1 New
A 1 1
A 0 1
A 0 1
B 0 1
B 1 1
B 0 1
C 0 0
C 0 0
【问题讨论】:
-
你能显示你想要的输出,这个函数是如何使用的等等吗?我做不到。
-
你为什么不直接
DF %>% group_by(UID) %>% fill(NewCol1) %>% fill(NewCol1, .direction = 'up')? -
我无法运行此功能。请在此处显示您正在使用的所有软件包。并用语言解释你想做什么。如果我们能理解它的实际作用以及如何运行它,您的代码可以很容易地加速。
-
我也无法运行你的函数。获取
Error: Can't use matrix or array for column indexing。 -
这是一种简单有效的方法,无需使用单个包,只需一步即可
DF[[NewCol1]] <- as.integer(DF$UID %in% DF[DF[[columnToUse]] == 1, "UID"])
标签: r performance function vectorization