populating a dataframe with for loop in R

I realise that there are similar questions to this one, but none of them have provided with me a solution to my problem.

I have made a function, which takes a year as argument and outputs a vectors with 8 elements:

> my_function(2004)
[1]  0  0  0  0 20 89  1  2

> my_function(2006)
[1]   0   0   0   0  83 205   0   1

I have attempted to create a for-loop, which would take all the output vectors for each year and convert them to columns in a dataframe:

ma <- matrix(ncol = 2, nrow = 8)
df <- data.frame(ma)
colnames(df)<-c(2004,2006)

for (i in c(2004,2006)){
df$`i` <- my_function(i)
}

I was expecting the output to look like this:

> df
  2004 2006
1    0    0
2    0    0
3    0    0
4    0    0
5   20   83
6   89  205
7    1    0
8    2    1

But instead the for loop just creates a new column called i and populates it with the last iteration:

 > df
  2004 2006   i
1   NA   NA   0
2   NA   NA   0
3   NA   NA   0
4   NA   NA   0
5   NA   NA  83
6   NA   NA 205
7   NA   NA   0
8   NA   NA   1

What I am doing wrong?

Best, Rikki

Upvotes: 0

Views: 45

Answers (1)

You can't use $ that way, it uses non-standard evaluation. Use [[ instead, so you can use df[[i]], with the note that you should then loop over c("2004", "2006"), otherwise your data.frame will end up with 2006 columns (but you might want to avoid using only numbers as column names anyway).

ma <- matrix(ncol = 2, nrow = 8)
df <- data.frame(ma)
colnames(df) <- c("2004", "2006")

for (i in c("2004", "2006")) {
  df[[i]] <- my_function(i)
}

– Axeman

Upvotes: 1

Related Questions