dimanche 18 février 2018

R dataframe calculation, anchor cell value to formula

R3.4.1 - Windows 10 - Hello, I would like to do some calculations with this dataframe:

x <- c ("1", "2","3", "4")
z <- (rep(x,5))
batch <- sort(z)
NDF <- rnorm(20, 10, 1)
Fibre_analysis <- data.frame(batch, NDF)
Fibre_analysis$NDF[[1]] <- 10
Fibre_analysis$NDF[[6]] <- 100
Fibre_analysis$NDF[[11]] <- 1000
Fibre_analysis$NDF[[16]] <- 10000

I would like this to create a new column in the dataframe, with absolute cell values from $NDFthat have to change for each value of $batch.

Because I need to use this process more than once I created the following function:

batch_Function <- function (x,y){
        ifelse (x =="1", y[[1]],
                ifelse (x =="2", y[[6]],
                        ifelse (x =="3", y[[11]],
                                y[[16]] )))
        print (y)
}

when I call the function:

Fibre_analysis$NEW_column <- batch_Function ( Fibre_analysis$batch , Fibre_analysis$NDF )

I expect $NEW_column to look like this:

x <- c(10,100,1000,10000)
NEW_column <- rep(x, each=5)

whereas instead it is the exact same copy of the NDF.

Help will be very much appreciated, many thanks.

Mauro

Aucun commentaire:

Enregistrer un commentaire