I have the following R function that checks a range of values and writes out a sentence about them. The problem is when I use the function and then call it all the sentences are the same regardless of Value.
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
Any ideas as to how to fix this problem.
Here is sample data:
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
Here is what I have at present:
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")
Hope this helps.
There are many problems with this :
1) you're using a function without arguments, and hope it does something with the variables in your global environment. That's dangerous.
2) the function isn't returning anything. Actually it is : it returns the last assignment, but I'm positive you're not aware of this, so in any case you better always include a return()
clause.
3) an if()
clause is not vectorized, so it only uses the first condition. In your case it only tests the first row of df.
5) &&
and ||
are used if you only want to test the first value of a series. The ones you need here is &
and |
(see ?"&"
in R)
5) Don't call your dataframe df, df()
is a function.
To do what I guess you want to do, try this :
#Sample data for testing
Df <- data.frame(Value = rnorm(100,140,10),
Change = rnorm(100,90,90),
YVoltage = rnorm(100,0.10,0.30))
hover <- function (X){
out <- ifelse((X$Value > 140 & X$Change < -0.05),
"Price High, Level of Activity Low",
ifelse((X$Value < 140 & X$Change > 90 &
X$YVoltage > -0.05 & X$YVoltage < 0.30),
"Price Normal, Level of Activity normal",
"Price High, Level of Activity high"
))
return(out)
}
hovertext <- hover(Df)
hovertext
精彩评论