【发布时间】:2016-11-25 19:48:06
【问题描述】:
我一直在尝试使用 R 自动化我的部分工作流程。我必须定期在我正在使用的数据集中使用转换。
我已经创建了一个使用可选参数的小函数,以便可以转换传递的数据帧的全部或部分列。
函数现在看起来像这样:
# Function:
# transformDivideThousand(dataframe, optional = vectorListOfVariables)
#
# Definition: This function applies a transformation, dividing variables by
# 1000. If the vector is passed it applies the transformation to all variables
# in the dataframe.
#
# Example: df <- transformDivideThousand (cases, c("label1","label2"))
#
# Source: http://stackoverflow.com/a/36912017/4417072
transformDivideThousand <- function(data_frame, listofvars){
if (missing(listofvars)) {
data_frame[, sapply(data_frame, is.numeric)] =
data_frame[, sapply(data_frame, is.numeric)]/1000
} else {
for (i in names(data_frame)) {
if (i %in% listofvars) {
data_frame[,i] = data_frame[,i]/1000
}
}
}
return(data_frame)
}
好的,现在我面临一个问题,我必须应用一个相当复杂的转换。这次应该:
- 反映存储在变量中的分数(即,找到最大值并将其从所有其他值中减去);
- 将结果加一;
- 平方根得到的分数;
- 取消反映分数(现在将与第一步中减去的相同值相加)
所有这些都应该发生,以保持在给定数据集的所有或部分列中运行函数的能力。
我找到了一种在SO 处使用一个小函数创建具有最大值的数据帧子集的方法:
colMax <- function(data) sapply(data, max, na.rm = TRUE)
但是我在 transformDivideThousand 中应用它时遇到了各种各样的问题。
问题
我真的在代码上苦苦挣扎,到目前为止,试图对问题进行建模,我达到了以下几点:
transformPlusOneSqrt <- function(data_frame, listofvars){
if (missing(listofvars)) {
# Find the largest value
data_frame_max <- data_frame
colMax <- function(data) sapply(data, max)
data_frame_max <- colMax(data_frame_max)
# Subtract the previous value
data_frame[, sapply(data_frame, is.numeric)] =
data_frame[, sapply(data_frame, is.numeric)] -
data_frame_max[,sapply(data_frame_max, is.numeric)]
# Plus one
data_frame[, sapply(data_frame, is.numeric)] =
data_frame[, sapply(data_frame, is.numeric)] + 1
# Sqrt
data_frame[, sapply(data_frame, is.numeric)] =
sqrt(data_frame[, sapply(data_frame, is.numeric)])
# Now, dereflect
data_frame[, sapply(data_frame, is.numeric)] =
data_frame[, sapply(data_frame, is.numeric)] +
data_frame_max[,sapply(data_frame_max, is.numeric)]
} else { ### This part is untouched
for (i in names(data_frame)) {
if (i %in% listofvars) {
data_frame[,i] = data_frame[,i]/1000
}
}
}
return(data_frame)
}
但这不起作用,因为我得到了:
> teste<- transformPlusOneSqrt(semDti)
Show Traceback
Rerun with Debug
Error in Summary.factor(c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, :
‘max’ not meaningful for factors
问题
我希望得到有关如何在一个函数中实现这种相当复杂的多任务转换的指针。我不是在寻找代码,只是在寻找指针和建议。
谢谢。
【问题讨论】:
标签: r