user11740857
user11740857

Reputation: 480

For loop in R for dataframe column

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"

Upvotes: 0

Views: 44

Answers (2)

Peace Wang
Peace Wang

Reputation: 2419

In your case, loop is not necessary.

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

Upvotes: 0

AnilGoyal
AnilGoyal

Reputation: 26238

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"

Upvotes: 1

Related Questions