Home > Enterprise >  How can I dissolve problem with convert For loop to R function?
How can I dissolve problem with convert For loop to R function?

Time:01-31

when I made for loop to calculate shapiro test of each row of matrix fro loop working as good but when make a function it was return character no number and don't work

# this for loop is goog
S_values <- matrix("list", nrow(d_L))
for(i in 1: nrow(d_L)) {
    S_values[i] = shapiro.test(d_L[i,])$p.value
}
# the function from loop not work
shapiro_test_rows<- function(input, output ) {
  output <- matrix("list", nrow(input))

  for(i in 1: nrow(input)) {
    output[i] = shapiro.test(input[i,])$p.value
  }
}
  
shapiro_test_rows(d_L, S_values )

Thanks

CodePudding user response:

If we need to create objects in the global env, use assign, though it is not recommended

shapiro_test_rows<- function(input, output ) {
  out <- deparse(substitute(output))
  output <- matrix("list", nrow(input))

  for(i in 1:nrow(input)) {
    output[i] = shapiro.test(input[i,])$p.value
  }
  assign(out, output, envir = .GlobalEnv)
}

-testing

> shapiro_test_rows(d_L, S_values)
> S_values
     [,1]                
[1,] "0.806971940138566" 
[2,] "0.0462406276029567"
[3,] "0.602353840880801" 
[4,] "0.692893270682741" 
[5,] "0.998560063995041" 

The output is character matrix because of the way the output object was initialized - i.e. the list is not doing what it should be intended

str(matrix("list", 5))
 chr [1:5, 1] "list" "list" "list" "list" "list"

Creates a character matrix` with element as "list"

instead we could simply create a matrix

shapiro_test_rows<- function(input, output ) {
  out <- deparse(substitute(output))
  output <- matrix(nrow = nrow(input))

  for(i in 1: nrow(input)) {
    output[i] = shapiro.test(input[i,])$p.value
  }
  assign(out, output, envir = .GlobalEnv)
}

-testing

> shapiro_test_rows(d_L, S_values)
> 
> S_values
           [,1]
[1,] 0.80697194
[2,] 0.04624063
[3,] 0.60235384
[4,] 0.69289327
[5,] 0.99856006

data

set.seed(24)
d_L <- matrix(rnorm(5 * 4), 5, 4)
  •  Tags:  
  • Related