0

I have a "for loop" in a R script. As a result, I obtain a list of a variable number of identifiers at the end of each loop. My question is simple: which is the best way to safe this information? When I do for loops with numeric vectors I can use vector[i] and gets saved in the position, but here I have a list of variable number of characters. The final table I would like to have would be a csv table, since I cannot use data.frame for the variable lenght. Each column would be one step of the for loop and each row would be the list of identifiers extracted in that particular loop step.

I try to put an example (it is not working, but it is my best try!) and how I would like to have the result:

a=c("a","b","c","d","e","f","g","h","i")
b=c(1,2,1,1,2,3,1,3,3)
data=data.frame(a,b)
i=0
k=0
res=0
for (i in 1:3){
k=data[data$b==i,]
res[i]=k$a
}
res

The result I would like to obtain would be like in the picture:

enter image description here

Thanks and sorry for my first message! First time asking questions in this community :)

Rayko87
  • 11
  • 3
  • 1
    Please create a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Conor Neilson Mar 24 '20 at 20:09
  • This is quite a bit of *telling* and not enough *showing*. Please include sample data, `for` loop code attempt, and desired result to better illustrate needs. – Parfait Mar 24 '20 at 21:58
  • Sorry, I edited the message in order to put an example and a (bad) try! – Rayko87 Mar 25 '20 at 00:29

1 Answers1

0

You don't need a loop. You can reshape the data to wide format and then save as csv treating the NA values as blank.

data$id <- with(data, ave(b, b, FUN = seq_along))
res <- reshape(data = data, direction = "wide", idvar = "id", timevar = "b" )
write.csv(res[-1], file = "mycsv.csv", na = "", row.names = FALSE)
Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56