动态地将元素添加到R中列表的组件

时间:2022-06-13 21:20:13

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

如何动态地在R中的列表组件中添加元素?

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.

例如,我有一个名为“mylist”的列表,其中包含两个组件,一个名为“number”,另一个名为“numberPowerTwo”,如下所示,需要在每个循环周期中将1个元素添加到我的mylist列表的每个组件中。

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).

我不知道这段代码是否有效,因为我不知道如何在文件中打印结果(使用write或write.table)。

1 个解决方案

#1


2  

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:

要作为文件输出,它取决于您想要的格式。结果是一个列表,我会推荐RData:

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

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

然后你可以简单地加载('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.

或者您可能需要一个excel文件,如果您有包xlsx,您可以将mylist的每个元素输出为一个工作表,并将所有元素一起输出为一个文件。否则,您只需为mylist的每个元素write.csv。

# 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'))
}

#1


2  

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:

要作为文件输出,它取决于您想要的格式。结果是一个列表,我会推荐RData:

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

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

然后你可以简单地加载('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.

或者您可能需要一个excel文件,如果您有包xlsx,您可以将mylist的每个元素输出为一个工作表,并将所有元素一起输出为一个文件。否则,您只需为mylist的每个元素write.csv。

# 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'))
}