这是我的功能:
adjusted <- c()
Adjustment <- function(delta, length) {
adjusted <<- vector_1 + delta*(index <= length)
head(adjusted)
}
以下是我想要实现的一个硬编码示例:
adjusted <- c()
Adjustment <- function(delta, length, group = 1) {
adjusted <<- vector_1[1:100] + delta*(index <= length)
head(adjusted)
}
我想实现一个参数或循环,它在输入的组参数值的vector_1的相应范围内执行计算。例如,如果我改为输入group = 2,则该函数将如下所示:
adjusted <- c()
Adjustment <- function(delta, length, group = 2) {
adjusted <<- vector_1[101:200] + delta*(index <= length)
head(adjusted)
}
我将如何实现这一目标?
我发现dplyr包可能对此有用,但我没有成功实现它。
非常感谢任何见解!
答案 0 :(得分:0)
我不确定delta
index
或length
是什么,所以我做了一些假设。
此外,由于您没有提供任何虚拟数据,我已经做了一些。
library(tidyverse)
# dummy data
dts <- rep(1:100,100)
region <- as.factor(rep(1:100, each = 100))
vec1 <- 1:10000
df <- as.data.frame(cbind(dts, region, vec1))
adjusted <- c()
Adjustment <- function(df, index, delta, length, selectRegion= 2) {
subDf <- df %>%
filter(region == selectRegion)
adjusted <<- subDf$vec1 + delta*(index <= length)
head(adjusted)
}
Adjustment(df, index = 2, delta = 2, length = 2, selectRegion = 4)
## run function for all levels of selectRegion
res <- lapply(levels(region), Adjustment, df = df, index = 2, delta = 2, length = 2)
## add names to list elements
names(res) <- paste0("adjustment_", 1:length(res))
res
$adjustment_1
[1] 3 4 5 6 7 8
$adjustment_2
[1] 103 104 105 106 107 108
$adjustment_3
[1] 203 204 205 206 207 208
$adjustment_4
[1] 303 304 305 306 307 308
$adjustment_5
[1] 403 404 405 406 407 408
Output keeps going to the 100th region.
答案 1 :(得分:0)
要获得附加图像中显示的结果,最简单的解决方案是获取每个区域的最小值并从区域中的所有条目中减去该值,然后添加1:
minimalValues <- tapply(yourData$index_value, yourData$region, min)
index_value2 <- yourData$index_value - minimalValues[yourData$region] + 1
如果你想做这个&#34;模块化&#34;你可以定义一个像
这样的函数resetDate <- function(regn, yourData) {
vals <- yourData$index_value[yourData$region == regn]
yourData$index_value[yourData$region == regn] <- vals - min(vals) + 1
}