Nimzo
Nimzo

Reputation: 492

Growing a list inside a for loop returns NAs

I would like to take back some indexes using a for loop and right now, the loop returns only NAs.

df <- data.frame(v1 = c("a", "b", "c", "d", "e"),
                 v2 = c("f", "g", "h", "i", "j"),
                 v3 = c("aa", "bb", "cc", "bb", "dd"))

vec <- c("aa", "bb", "ee")

res <- list()


for (i in(vec)){
 temp <- vec[i]
 res[[i]] <- grep(temp, df[,3])
}

gives

res

$aa
[1] NA NA NA NA NA

$bb
[1] NA NA NA NA NA

$ee
[1] NA NA NA NA NA

while I am struggling for this

res

$aa
[1] 1

$bb
[1] 2 4

$ee
[1]

What is this very simple thing that I keep being unaware of?

Upvotes: 2

Views: 126

Answers (2)

Eric
Eric

Reputation: 2849

df <- data.frame(v1 = c("a", "b", "c", "d", "e"),
                 v2 = c("f", "g", "h", "i", "j"),
                 v3 = c("aa", "bb", "cc", "bb", "dd"))

vec <- c("aa", "bb", "ee")

sapply(vec, grep, df$v3)
#> $aa
#> [1] 1
#> 
#> $bb
#> [1] 2 4
#> 
#> $ee
#> integer(0)

Upvotes: 2

akrun
akrun

Reputation: 887571

We can use lapply to loop over the pattern vector, invoke the grep specify the argument 'x' as 'v3' column

lapply(vec, grep, x = df$v3)

Or use anonymous function call

lapply(vec, function(pat) grep(pat, df$v3))

The list res can be initialized in OP's post as

res <- vector('list', length(vec))

then loop over the sequence of the 'vec'

for (i in seq_along(vec)){
   temp <- vec[i]
   res[[i]] <- grep(temp, df[,3])
  }

Upvotes: 3

Related Questions