如何引用列表中数据框中的行/列? [英] How do i refer to rows/ columns in data frames that are within a list?

查看:192
本文介绍了如何引用列表中数据框中的行/列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用列表中的数据框.尽管我目前正在尽最大努力,但我收到的下标数量不正确"和类似的错误.这是我的代码:

I'm looking to work with the data frames I have within a list. I'm getting 'incorrect number of subscripts' and similar errors, despite my current best efforts. Here's my code:

folder = 'C:/Path to csv files-071813/'
symbs = c('SPX', 'XLF', 'XLY', 'XLV', 'XLI', 'IYZ', 'XLP', 'XLE', 'XLK', 'XLB', 'XLU', 'SHV')
importData = vector('list', length(symbs))
names(importData) = symbs

for (sIdx in 1:length(symbs)){
    #Import the data for each symbol into the list.
    importData[sIdx] = read.csv(paste(folder, symbs[sIdx], '.csv', sep = ''), header = TRUE)

}

每个csv文件包含数千行和7列. 我假设以上内容是将每个csv文件的数据帧返回到我的列表中. 我想输入:

Each csv file is thousands of rows, and 7 columns. I'm assuming what I have above is returning a data frame from each csv file, into my list. I'd like to enter:

importData[[1]][, 1]

与列表中第一个数据框的第一列一起使用.我靠近吗?尽管进行了所有搜索,但仍找不到分辨率.提前非常感谢...

to work with the first column of the first data frame in my list. Am I close? I can't find resolution despite all my searching. Many thanks in advance...

推荐答案

apply函数家族将在这里成为您的朋友,特别是lapply,该函数给出了列表和函数,将函数对该列表的每个元素进行操作,并将结果作为新列表的元素返回.

The apply family of functions are going to be your friend here, specifically lapply, a function which, given a list and a function, applies the function to every element of that list and returns the results as elements of a new list.

folder = 'C:/Path to csv files-071813/'
symbs = c('SPX', 'XLF', 'XLY', 'XLV', 'XLI', 'IYZ', 'XLP', 'XLE', 'XLK', 'XLB', 'XLU', 'SHV')
filenames = paste0(folder,symbs,'.csv')
listOfDataframes=lapply(filenames,read.table,header=T)

现在,如果您想从所有数据框中获取第二列,则可以执行类似

Now if you want the second column from all the dataframes you could do something like

listOfFirstCols=lapply(listOfDataframes,"[",,2)

或更明确地

listOfFirstCols=lapply(listOfDataframes,function(x)x[,1])

这篇关于如何引用列表中数据框中的行/列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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