在 for 循环中提取数据并将其附加到新数据集

Extract and append data to new datasets in a for loop

我有(我的想法)是一个非常简单的问题,但我不知道该怎么做。我对列表、循环等还很陌生

我有一个小数据集:

df <- c("one","two","three","four")
df <- as.data.frame(df)
df

我需要遍历此数据集并创建一个数据集列表,结果如下:

[[1]]
one

[[2]]
one
two

[[3]]
one
two
three

这大概是我得到的:

blah <- list()

for(i in 1:3){
  blah[[i]]<- i
}

以后用这个的时候长度是可变的,所以需要循环自动化。不然我就干

one <- df[1,]
two <- df[2,]

list(one, rbind(one, two))

有什么想法吗?

基础 R 解决方案:

# Coerce df vector of data.frame to character, store as new data.frame: str_df => data.frame 
str_df <- transform(df, df = as.character(df))

# Allocate some memory in order to split data into a list:  df_list => empty list
df_list <- vector("list", nrow(str_df))

# Split the string version of the data.frame into a list as required: 
# df_list => list of character vectors
df_list <- lapply(seq_len(nrow(str_df)), function(i){
    str_df[if(i == 1){1}else{1:i}, grep("df", names(str_df))]
  }
)

数据:

df <- c("one","two","three","four")
df <- as.data.frame(df)
df

您可以尝试使用 lapply :

result <- lapply(seq(nrow(df)), function(x) df[seq_len(x), , drop = FALSE])
result

#[[1]]
#   df
#1 one

# [[2]]
#   df
#1 one
#2 two

#[[3]]
#     df
#1   one
#2   two
#3 three

#[[4]]
#     df
#1   one
#2   two
#3 three
#4  four

seq(nrow(df)) 创建一个从 1 到数据行数(在本例中为 4)的序列。 function(x) 部分被称为匿名函数,其中从 1 到 4 的每个值都被一一传递。 seq_len(x) 创建一个从 1 到 x 的序列,即第一次迭代中的 1 到 1,第二次迭代中的 1 到 2,依此类推。我们使用此序列对数据帧 (df[seq_len(x), ]) 中的行进行子集化。由于数据框在我们对它进行子集化时只有 1 列,因此它会将其更改为向量。为了避免这种情况,我们添加 drop = FALSE.