我有以下R函數檢查一系列值並寫出關於它們的句子。問題是,當我使用函數,然後調用它的所有句子都是相同的,不管值是多少。使用if語句的函數只返回一個其他條件而不管值
hover <- function(){
if(df$Value > 140 && df$Change < -0.05){
hovertext ="Price High, Level of Activity Low"
}else{
if(df$Value < 140 && df$Change > 90 && df$YVoltage > -0.05 &&
df$YVoltage < 0.30){
hovertext ="Price Normal, Level of Activity normal"
} else {
hovertext ="Price High, Level of Activity high"
}
}
}
hovertext <- hover()
hovertext
有關如何解決此問題的任何想法。
這裏是樣本數據:
TimeStamp,Price,Change
12:00:00,140,0.05
12:12:03,148,0.06
12:12:40,130,-0.05
12:12:50,135,0.01
12:13:00,135,0
12:13:10,1.37,0.01
這裏是我目前:
library (ggplot2)
df <- read.csv(file.choose(), header =TRUE)
df
df$Price <- as.numeric(as.character(df$Price))
df$Change <- as.numeric(as.character(df$Change))
df$TimeStamp <- strptime(as.character(df$TimeStamp), "%H:%M:%OS")
sapply(df, class)
options("digits.secs"=3)
summary (df)
df$TimeStamp <- df[1,"TimeStamp"] +
cumsum(runif(1:length(df$TimeStamp))*60)
summary(df)
hover <- function (df){
out <- ifelse((df$Value > 140 & df$Change < -0.05),
"Price High, Level of Activity Low",
ifelse((df$Value < 140 & df$Change > 90 &&
df$YVoltage > -0.05 & df$Change < 0.30),
"Price Normal, Level of Activity normal",
"Price High, Level of Activity high"
))
return(out)
}
hovertext <- hover(df)
hovertext
sink (file="c:/Users/user/text.txt", type="output",split=FALSE)
cat(sprintf(" Time=\"%s\" value=\"%f\" hoverText =\" %s\" ></set>\n",
df$TimeStamp, df$Price, hovertext))
unlink("text.txt")
希望這有助於。
沒有什麼進入你的功能?至少應該爲你的函數指定一個參數。如果你提供一些樣本數據,這將是很好的。 – 2010-09-14 08:13:10