我在R中遇到了很大的性能问题.我编写了一个迭代data.frame对象的函数.它只是添加一个新列data.frame并积累一些东西.(操作简单).将data.frame有大约850K行.我的电脑仍在工作(现在大约10小时),我不知道运行时间.
dayloop2 <- function(temp){
for (i in 1:nrow(temp)){
temp[i,10] <- i
if (i > 1) {
if ((temp[i,6] == temp[i-1,6]) & (temp[i,3] == temp[i-1,3])) {
temp[i,10] <- temp[i,9] + temp[i-1,10]
} else {
temp[i,10] <- temp[i,9]
}
} else {
temp[i,10] <- temp[i,9]
}
}
names(temp)[names(temp) == "V10"] <- "Kumm."
return(temp)
}
Run Code Online (Sandbox Code Playgroud)
有什么想法如何加快这个操作?
......关于执行时间和/或记忆.
如果不是这样,请使用代码段进行证明.请注意,矢量化的加速不计算在内.增速必须来自apply(tapply,sapply,...)本身.
我想在数据框中为每个组创建一个单独的绘图,并在标题中包含该组.
使用虹膜数据集,我可以在基础R和ggplot中执行此操作
plots1 <- lapply(split(iris, iris$Species),
function(x)
ggplot(x, aes(x=Petal.Width, y=Petal.Length)) +
geom_point() +
ggtitle(x$Species[1]))
Run Code Online (Sandbox Code Playgroud)
是否有使用dplyr的等价物?
这是尝试使用facet而不是title.
p <- ggplot(data=iris, aes(x=Petal.Width, y=Petal.Length)) + geom_point()
plots2 = iris %>% group_by(Species) %>% do(plots = p %+% . + facet_wrap(~Species))
Run Code Online (Sandbox Code Playgroud)
其中我使用%+%将p中的数据集替换为每个调用的子集.

或者(工作但复杂)与ggtitle
plots3 = iris %>%
group_by(Species) %>%
do(
plots = ggplot(data=.) +
geom_point(aes(x=Petal.Width, y=Petal.Length)) +
ggtitle(. %>% select(Species) %>% mutate(Species=as.character(Species)) %>% head(1) %>% as.character()))
Run Code Online (Sandbox Code Playgroud)

问题是我似乎无法以非常简单的方式使用ggtitle为每个组设置标题.
谢谢!
我知道在R中使用for循环并不是最好的做法,因为它没有增强的性能.对于几乎所有情况,家庭都有*apply解决我们问题的功能.
但是我面临着一种我没有看到解决方法的情况.
我需要计算连续值的百分比变化:
pv[1] <- 0
for(i in 2:length(x)) {
pv[i] <- (x[i] - x[i-1])/x[i-1]
}
Run Code Online (Sandbox Code Playgroud)
所以,正如你所看到的,我必须既使用x[i]元素,也使用x[i-1]元素.通过使用这些*apply功能,我只看到如何使用x[i].无论如何,我可以避免for循环?
我想将大型数据框子集化并创建每个分组的ggplot.听起来像是dplyr的完美候选者,但我遇到了在group_by结果上调用函数的问题.任何提示将不胜感激.
# what I want to do using base functions: "groupby" the elements in a column
# and create/save a plot for each group
for (i in levels(iris$Species)){
df = iris[iris$Species == i,]
p <- ggplot(df, aes(x=Sepal.Length, y=Sepal.Width) + geom_point())
ggsave(p, filename=paste(i,".pdf",sep=""))
}
# I'm trying to get something like this using dplyr
library(dplyr)
iris %>%
group_by(Species) %>%
do({
p <- ggplot(., aes(x=Sepal.Length, y=Sepal.Width) + geom_point())
ggsave(p, filename=paste(quote(Species),".pdf",sep=""))
})
Run Code Online (Sandbox Code Playgroud)