0

This seems to be a basic problem. I am attempting to loop through a list of variables to determine the shapiro-wilk statistic. However, the var is not registering anything in the loop. It appears as "NULL (empty)" in the environment window of RStudio.

The test works fine outside of the for loop. Any thoughts on what needs to be corrected here?

library(broom)    
data = "some data.csv"    
vars = list("var1", "var2")
     for (var in names(vars)) {    
          sw <- tidy(shapiro.test(data$var))
          write.csv(sw, file = "shapirowilk_pvalue_" + var + ".csv")
}

Thanks in advance

EDIT1 Following the advice in the comments, the revised (and now working) code is:

vars = c("var1", "var2")
for (var in vars) {
  sw <- tidy(shapiro.test(Data[[var]]))

The syntax for the write.csv is not working...

EDIT2 The full working code is below, which writes to a text file:

sw_pvalues <- data.frame()
vars = c("var1", "var2")
for (var in vars) {

  sw <- tidy(shapiro.test(Data[[var]]))

  tempvalues <- cbind(var,sw)
  colnames(tempvalues) <- c('variable', 'sw_stat', 'pvalue', 'method')
  sw_pvalues = rbind(sw_pvalues, tempvalues)

}
write.csv(sw_pvalues, file = "shapirowilk_pvalues.csv")
11
  • 1
    data$var is shorthand for the data's "var" column (which doesn't exist). You want to use data[[var]]. Commented Sep 15, 2017 at 18:07
  • Try using the data[[var]] instead of data$var. One needs to programmatically access the variable. Commented Sep 15, 2017 at 18:07
  • Also, (I'm not sure if your code is just pseudo code, but) names(list('var1', 'var2')) evaluates to NULL, so that might be impacting your for loop. Commented Sep 15, 2017 at 18:09
  • I switched to [[var]] but no change in the output. It seems that var1 should be set in the for line, regardless of how the shapiro test is specified. Commented Sep 15, 2017 at 18:17
  • The elements of the list (var1 and var2) are field headings of the data table. Commented Sep 15, 2017 at 18:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.