简体   繁体   English

r-从数据帧循环创建矩阵

[英]r - create matrix from data frame loop

I have many data frames id.1, id.2, ... ,id.21 and in each of which I want to extract 2 data points: id.1[5,4] and id.1[10,6] , id.2[5,4] and id.2[10,6] , etc. The first data point is a date and the second data point is a integer. 我有很多数据帧id.1, id.2, ... ,id.21 ,我想在每个数据帧中提取2个数据点: id.1[5,4]id.1[10,6]id.2[5,4]id.2[10,6]等。第一个数据点是日期,第二个数据点是整数。

I want to export this list to obtain something like this in an .csv file: 我想导出此列表以获得.csv文件中的类似内容:

        V1          V2
1    5/10/2016      1654395291
2    5/11/2016      1645024703
3    5/12/2016      1763825219

I have tried 我努力了

 x=c(for (i in 1:21) {
            file1 = paste("id.", i, "[5,4]", sep="")}, for (i in 1:21) {
            file1 = paste("id.", i, "[10,6]", sep="")})
 write.csv(x, "x.csv")

But this yields x being NULL . 但是,这导致xNULL How can I go about getting this vector? 我该如何获得该向量?

Your problem is that a for loop doesn't return anything in R. So you can't use it in a c statement as you did. 您的问题是for循环不会在R中返回任何内容。因此,您不能像以前那样在c语句中使用它。 Use an [sl]apply construct instead. 请改用[sl]apply构造。

I would first make a list containing all the data frames: 我将首先列出所有数据帧:

dfs <- list(id.1, id.2, id.3, ...)

And iterate over it, something like: 并对其进行迭代,如下所示:

x <- sapply(dfs, function(df) {
  return(c(df[5,4], df[10,6]))
})

Finally you need to transpose the result and convert it into a data.frame if you want to: 最后,如果需要,您需要转置结果并将其转换为data.frame

x <- as.data.frame(t(x))

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

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