在R中使用for循环创建数据帧

时间:2019-01-09 21:07:00

标签: r string loops object

我想编写一个循环,在R中创建五个新数据集,每个数据集中包含与原始数据帧df不同数量的观察值。

这是我当前的代码,它以字符串而不是实际对象(“ df [4:42 + i]”而不是df [4:42 + i])的形式输出dfi的值。

for(i in 1:5)
{  nam <- paste("df",i, sep="")
assign(nam, eval(paste("df","[1:44 + ",i,",]", sep="")))
}

我想在循环时返回df对象,但是我不知道该怎么做。有什么建议么?预先非常感谢。

2 个答案:

答案 0 :(得分:0)

给出示例数据集:

df <- mtcars

这是框架列表:

list_of_frames <- lapply(1:5, function(i) df[1:3 + i,])
list_of_frames[[3]]
#                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

(如果您真的喜欢这些名称,也可以

names(list_of_frames) <- paste0("df", 1:5)
list_of_frames[["df3"]]

如果您确实需要将每个变量分开,那么这里是循环:

ls() # proof that they don't exist yet
# [1] "df"
for (i in 1:5) assign(paste0("df", i), df[1:3 + i,])
ls()
# [1] "df"  "df1" "df2" "df3" "df4" "df5" "i"  
df3
#                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

答案 1 :(得分:0)

I take this as sampling a data frame n number of times with repeating being okay. You can do this with lapply and some tidyverse.

floor(runif(5, 10, 30))

This generates 5 integers from 10 to 30. Change these as you like.

function(x) mtcars %>% sample_n(x)

This takes a dataframe (mtcars), and samples some number of rows from the dataframe.

lDF <- lapply(floor(runif(5, 10, 30)), function(x) mtcars %>% sample_n(x))

This puts it together using lapply with creates a list of dataframes that you can reference as lDF[1] as you like

相关问题