i'd appreciate your help on something that is currently driving me crazy. I'm processing some data regarding different characteristics with a loop & everything besides this particular function is working properly:
fun<-function(X)
{
Y <- numeric()
if(max(X)== X[1]){Y<-0}else{Y=X[which.max(X)-1]}
return(Y)
}
so:
say, I got 5 different csv.-files in my directory, which i'm refering to. in a certain row there are values, which im comparing with the expression
X[which.max(X)-1]
So for instance I have got 3 values in my file:
3.5;6.4;7.1 -> the function should give me 6.4
2.8;1.6;2.3 -> the function should give me 0
... and so on.
The function itself is working, but for 5 different files I always get the same output-value. In this case I would get five time 6.4 . So it just repeats the very first output and does not actually consider the values of the second file.
I hope i explained my problem accurate and would appreciate hints and suggestions :)
the entire code:
setwd("C:\\Users")
data = list.files(pattern="*.csv", full.names= TRUE)
data
t = length(data)
output= data.frame(Output1=NA)
for (i in 1:t) {
Characteristics <- read.csv(file=data[i], sep=";", nrows = 22)
Duration = as.character (Characteristics [8,1])
Duration = as.numeric(strsplit(Duration," ") [[1]][4])
X = as.character(Characteristics [9:(8+Duration),1])
X = as.numeric (X)
fun<-function(X)
{
Y <- numeric()
if(max(X)== X[1]){Y<-0}else{Y <- X[which.max(X)-1]}
return(Y)
}
Output1 = Y
output [i,1] <- Output1
}
cheers, Olli
答案 0 :(得分:1)
The fun
has not been used properly in code. First of all, the purpose of the fun
is not very clear and its not assigning any value to Y
either. If purpose of the fun
is to to find max value in X
and assign index of it to Y
. Then best option could be define the function separately.
# define fun as separate
fun <- function(X)
{
Y <- numeric()
if(max(X)== X[1]){Y<-0}else{Y <- X[which.max(X)-1]}
return(Y)
}
#Modify for-loop as
for (i in 1:t) {
Characteristics <- read.csv(file=data[i], sep=";", nrows = 22)
Duration = as.character (Characteristics [8,1])
Duration = as.numeric(strsplit(Duration," ") [[1]][4])
X = as.character(P_Char [9:(8+Duration),1])
X = as.numeric (X)
Output1 = fun(x)
output [i,1] <- Output1
}