r在for循环中创建和地址变量 [英] r create and address variable in for loop

查看:286
本文介绍了r在for循环中创建和地址变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文件夹中有多个csv文件。我想把这个文件夹中的每个csv文件放入一个单独的数据框。接下来,我想从这个数据框中提取某些元素为矩阵,并计算所有这些矩阵的平均值。

I have multiple csv-files in one folder. I want to load each csv-file in this folder into one separate data frame. Next, I want to extract certain elements from this data frame into a matrix and calculate the mean of all these matrixes.

setwd("D:\\data")
group_1<-list.files()
a<-length(group_1)

mferg_mean<-data.frame

for(i in 1:a)
{ 
assign(paste0("mferg_",i),read.csv(group_1[i],header=FALSE,sep=";",quote="",dec=",",col.names=1:90))
}


b $ b

由于文件夹中有11个csv文件,我现在有了数据框架。

As there are 11 csv-files in the folder I now have the data frames

mferg_1

mferg_11

如何解决此循环中的每个数据帧?如上所述,我想从每个数据帧中提取某些元素为矩阵。我会想象它是这样的:

How can I address each data frame in this loop? As mentioned, I want to extract certain elements from each data frame to a matrix. I would imagine it something like this:

assign(paste0("mferg_matrix_",i),mferg_i[1:5,1:10])

但这显然不起作用,因为R在循环中不能识别mferg_i。如何解决这个数据框?

But this obviously does not work because R does not recognize mferg_i in the loop. How can I address this data frame?

推荐答案

这不是你应该使用 / code>首先。在R中使用一堆不同的data.frames是一件麻烦,但使用data.frames的列表更容易。尝试使用

This is not something you should probably be using assign for in the first place. Working with a bunch of different data.frames in R is a mess, but working with a list of data.frames is much easier. Try reading your data with

group_1<-list.files()
mferg <- lapply(group_1, function(filename) { 
    read.csv(filename,header=FALSE,sep=";",quote="",dec=",",col.names=1:90))
})

,你会得到每个值 mferg [[1] code>, mferg [[1]] 等。然后你可以创建一个提取列表

and you get each each value with mferg[[1]], mferg[[1]], etc. And then you can create a list of extractions with

mferg_matrix <- lapply(mferg, function(x) x[1:5, 1:10])

这是更像R的做事方式。

This is the more R-like way to do things.

但在技术上你可以使用 get 来检索值,例如使用 assign 创建它们。例如

But technically you can use get to retrieve values like you use assign to create them. For example

assign(paste0("mferg_matrix_",i),get(paste0("mferg_",i))[1:5,1:10])

但是,这可能不是一个聪明的策略

but again, this is probably not a smart strategy in the long run.

这篇关于r在for循环中创建和地址变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆