In R: How to group the results of a loop into a rbind function?

Asked

Viewed 400 times

0

Whereas I have a dataframe called page whose number of lines varies regularly, I wrote this code so that it fits the number of lines that my page$id owns and wrote this while so that he manages a "g_com[numero]" for each of these lines.

meu page$id contém:
[1] "1793398447353793"
[2] "1792916894068615"
[3] "1792013524158952"
[4] "1791520780874893"
continua...

This is the script I’m running:

binds    <- as.data.frame(page$id)
contador <- 1

while (contador <= length(page$id)) { 
  binds[contador] <- paste0 ("g_com", contador)
  contador        <- contador + 1
}

b <- binds [1,]

It is returning a table with 17 columns and a row in each:

> print(binds)
page$id     V2     V3     V4     V5
1       g_com1, g_com2, g_com3, g_com4, g_com5,

However, I need to automatically group all these "g_com" in a sentence, so that it is without a comma after the last element and can be presented in a single row, and not in columns, I need to run a rbind on them, so I need it to return something like

g_com1, g_com2, g_com3, ..., g_com17

If anyone can help me, I’d appreciate it.

  • As I mentioned in your previous question, it is very difficult to help you with such a general question. Try to put yourself in the place of those who are reading the question, who do not know page, page$id and everything else. It’s complicated to test our solution proposals without a data set to apply it. See this list of answered questions about R and realize that the people who made them were objective, giving necessary information to those who were willing to help.

  • @Marcus Nunes, I tried to improve the question and the description of the data. Got better? Thanks again for the tips!

1 answer

1

I generated some random data because I don’t have access to the originals. See if the command paste(unlist(b[2:length(b)]), collapse=", "), at the end of the code, help yourself.

page <- data.frame(id=rpois(17, lambda=100000))

binds    <- as.data.frame(page$id)
contador <- 1

while (contador <= length(page$id)) { 
  binds[contador] <- paste0("g_com", contador)
  contador        <- contador + 1
}

b <- binds [1,]

print(b)
  page$id     V2     V3     V4     V5     V6     V7     V8     V9     V10
1  g_com1 g_com2 g_com3 g_com4 g_com5 g_com6 g_com7 g_com8 g_com9 g_com10
      V11     V12     V13     V14     V15     V16     V17
1 g_com11 g_com12 g_com13 g_com14 g_com15 g_com16 g_com17

paste(unlist(b[2:length(b)]), collapse=", ")
[1] "g_com2, g_com3, g_com4, g_com5, g_com6, g_com7, g_com8, g_com9, g_com10, 
g_com11, g_com12, g_com13, g_com14, g_com15, g_com16, g_com17"

I cannot see how the code provided generated the original data with commas, since the code is not reproducible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.