0

I am trying to apply a loop to extract vectors from dataframe columns. But failing. Can anyone help me

> df <- data.frame(sym = c("ABC","CGF","DFG"))
> com_list <- c(1:3)
for (j in com_list)
{
    com <- c()
    com <- c(com[j], paste0(df$sym[j], collapse=","))
}
> com
[1] "DFG"

Expected output

> com
"ABC,CGF,DFG"
1
  • com <- paste0(df$sym, collapse = ',') Commented Apr 10, 2021 at 4:48

2 Answers 2

1

For every iteration, first job i.e. com <- c() empties the com and then pastes ith element. So the output you are getting is only last element.

If you want to do it through for loop, take com <- c() outside of the loop and do it like this.

df <- data.frame(sym = c("ABC","CGF","DFG"))
com_list <- c(1:3)
com <- c()
for (j in com_list){
  
  com <- c(com, paste0(df$sym[j], collapse=","))
 }
com

[1] "ABC" "CGF" "DFG"
Sign up to request clarification or add additional context in comments.

Comments

0

In your case, loop is not necessary.

paste0(df$sym[com_list],collapse=",")
# "ABC,CGF,DFG"

Comments

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.