Visser Visser - 2 months ago 9
R Question

For loop outputting the wrong answer

The code below is an example. My function

testf
works fine when calling
NAME
or
SRC
individually but it doesn't work if I try to do this through a vector - make sense I believe. So I ventured into making it a loop and by rights (from what I do understand) this should work, but it hasn't. It generates an output but it's clearly wrong and I'm not sure why it's doing this. Am I applying this incorrectly? Thanks

NAME <- c("SYNOP", "SYNOP", "METAR", "METAR", "SYNOP", "METAR")
AIR <- c(6.7, 8.3, 9.2, 8.9, 9.1, 8.7)
SRC <- c("WMO", "WMO", "WMO", "ID_3", "ID_3", "WMO")
Example <- data.frame(NAME, AIR, SRC)

require(dplyr)
testf <- function(j) {
Example %>% group_by((j)) %>% summarize(Count=n())
}

testf(NAME)
testf(SRC)

vector <- c("NAME", "SRC")

testf(vector)

for (v in vector) {
testg <- testf(v)
print(testg)
}

Answer

To be able to pass a string to testf and have it passed on to group_by, you'd have to use the standard evaluation version, which is group_by_:

testf <- function(j) {
    Example %>% group_by_(.dots = j) %>% summarize(Count=n())
}

# examples:
testf("NAME")
testf(c("NAME", "AIR"))

for (v in c("NAME", "SRC")) {
  print(testf(v))
}