0

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

8
  • 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). Commented Oct 19, 2022 at 21:22
  • 2
    If you are looking for a non-loop solution too, try this: as.data.frame(lapply(c(2004, 2006), my_function)) Commented Oct 19, 2022 at 21:26
  • @Axeman. I works! Thanks a lot. However, I am very confused now, as I thought the double brackets were only used for accessing objects in lists? Secondly, I had no idea the a function takes both strings and numerals as arguments! Commented Oct 19, 2022 at 21:38
  • @B.ChristianKamgang. That is a beautiful simple solution! Thanks a lot. Commented Oct 19, 2022 at 21:44
  • Could someone please post the info from these comments as an answer? Commented Oct 19, 2022 at 21:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Nice. You should probably also post the code that actually works as part of your answer.
@BenBolker. Very good point. I will edit the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.