Guilherme Campos
Guilherme Campos

Reputation: 379

Add element to a component of a list in R dynamically

How can I add an element to a component of a list in R dynamically?

For example, supose I have a list called "mylist" with two components, one called "number" and the other called "numberPowerTwo", as following, and need to add 1 element in each loop cycle to each component of my mylist list.

N <- 10
mylist <- list(number = c(), numberPowerTwo = c())

for (i in 1:N){
    n <- i
    n2 <- i * i

    mylist[i]$number <- n
    mylist[i]$numberPowerTwo <- n2
}

I don't know if this code work because I don't know also how to print the result in a file (using write or write.table).

Upvotes: 0

Views: 615

Answers (1)

Sean Lin
Sean Lin

Reputation: 815

Try code below:

N <- 10
mylist <- list(number = c(), numberPowerTwo = c())

for (i in 1:N){
    n <- i
    n2 <- i * i

    mylist[['number']][i] <- n
    mylist$numberPowerTwo[i] <- n2
}

To output as a file, it depends on format you want. The result is a list, I would recommend RData:

save(mylist, file = 'mylist.RData')

then you can simply load('mylist.RData').

Or you may want an excel file, if you have package xlsx, you can output each element of mylist as one sheet and all together as one file. Otherwise, you can just write.csv for each element of mylist.

# one file with multiple sheets
for (i in 1:length(mylist)) {
    write.xlsx(mylist[[i]], 'mylist.xlsx', append = T, row.names = F, 
               sheetName = names(mylist)[i])
}
# separate files for each element
for (i in 1:length(mylist)) {
    write.csv(mylist[[i]], paste0(names(mylist)[i], '.csv'))
}

Upvotes: 2

Related Questions