我正在编写一个函数,它应该将数据帧作为输入,并重新调整数据框中的所有变量,使它们的最小值为1.我已经能够为向量执行此操作(请参阅代码在下面),但无法弄清楚如何为数据框执行此操作。换句话说,下面函数的输入是一个向量,输出是一个向量,但我希望(a)使这个输入是一个数据帧,输出是一个rescale变量的数据帧或(b)看如何将函数应用于数据框,以便在变量的最小值为1时将其写入原始变量。
这是我的功能:
min_to_one <- function(x) {
# require integer or numeric vectors
stopifnot(is.integer(x), is.numeric(x))
# Save the minimum of x
xmin <- min(x)
# Find the distance between minimum and 1
distance <- diff(c(xmin, 1))
# If the distance != 0, add the distance if
# x is negative and subtract if it is positive
ifelse(xmin != 1,
return(ifelse(xmin < 0, x + distance, x - distance)),
return(x)
)
}
我确信除了覆盖所有变量之外,还有更快的方法。例如,如下所示:
# Generate toy data frame
df <- data.frame(a=rnorm(5),
b = runif(5),
d = c("a","b","c","d","e"))
# Does the vector's min == 1?
min_equals1 <- function(x) {if(is.numeric(x) | is.integer(x)) min(x) == 1}
# Apply it (this returns a list rather than a vector, would like a vector so
# one can then specify that min_to_one() is only applied to the vectors where
# min(x) != 1
sapply(df, min_equals1)
有什么建议吗?