简体   繁体   English

在 R 中的循环中创建多个数据帧

[英]Creating multiple dataframes in a loop in R

I am new to R and I don't know how to create multiple data frames in a loop.我是 R 的新手,我不知道如何在循环中创建多个数据框。 For example: I have a data frame "Data" with 20 rows and 4 columns:例如:我有一个 20 行 4 列的数据框“数据”:

Data <- data.frame(matrix(NA, nrow = 20, ncol = 4))
names(Data) <- c("A","B","C","D")

I want to choose the rows of Data which its values in column T are the closest values to the vector elements of X.我想选择数据行,它在列 T 中的值是与 X 的向量元素最接近的值。

X = c(X1,X2,X3,X4,X5) 

Finally, I want to assign them to a separate data frames with their associated X name:最后,我想将它们分配给具有关联 X 名称的单独数据框:

for(i in 1:length(X)){ 
data_X[i] <- data.frame(matrix(NA))  
data_X[i] <- subset(data2, 0 <= A-X[i] | A-X[i]< 0.000001 )
}

Thank you!谢谢!

Since you didn't give us any numbers, it is difficult to say exactly what you need the for loop to look for.由于您没有给我们任何数字,因此很难确切说明您需要 for 循环查找什么。 As such, you will need to sort that out yourself, but here is a basic example of what you could do.因此,您需要自己解决这个问题,但这里有一个基本示例,说明您可以做什么。 The important part that I think you are missing is that you need to use assign to send the created dataframes to your global environment or wherever you want them to go for that matter.我认为您缺少的重要部分是您需要使用assign将创建的数据帧发送到您的全局环境或您希望它们去的任何地方。 Paste0 is a handy way to give them each their own name. Paste0是一种方便的方法,可以为它们各自命名。 Take note that some of the data frames will be empty.请注意,某些数据框将为空。 It may be worthwhile to use an if statement that skips assign ing the dataframe if (nrow(data3)==0) .使用if语句跳过数据帧if (nrow(data3)==0) assign可能是值得的。

`Data <- data.frame(matrix(sample(1:10,80,replace = T), nrow = 20, ncol = 4))`
`names(Data) <- c("A","B","C","D")`
`X = c(1:10)` 


`for(i in 1:length(X)){ 
  data2 <- Data 
  data3 <- subset(data2, A == X[i])
  assign(paste0("SubsetData",i), data3, envir = .GlobalEnv)
}`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM