使用lapply子集数据帧中的行-错误的维数错误 [英] Using lapply to subset rows from data frames -- incorrect number of dimensions error

查看:55
本文介绍了使用lapply子集数据帧中的行-错误的维数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"scenbase"的列表,其中包含40个数据帧,每个数据帧326行乘68列.我想使用lapply()子集数据帧,以便它们仅保留行33-152.我已经编写了一个名为trim()的简单函数(如下),并试图将其应用于数据帧列表,但收到一条错误消息.该函数以及我将其与lapply配合使用的尝试如下:

I have a list called "scenbase" that contains 40 data frames, which are each 326 rows by 68 columns. I would like to use lapply() to subset the data frames so they only retain rows 33-152. I've written a simple function called trim() (below), and am attempting to apply it to the list of data frames but am getting an error message. The function and my attempt at using it with lapply is below:

修剪<-函数(i) {(i<-i [33:152,])}

trim <- function(i) { (i <- i[33:152,]) }

lapply(场景,修剪)

lapply(scenbase, trim)

i [33:152,]中的错误:维数错误

Error in i[33:152, ] : incorrect number of dimensions

当我尝试对列表中的单个数据帧(soil11base.txt)之一执行以下操作(如下所示)时,它会按预期工作:

When I try to do the same thing to one of the individual data frames (soil11base.txt) that are included in the list (below), it works as expected:

soil11base.txt<-soil11base.txt [33:152,]

soil11base.txt <- soil11base.txt[33:152,]

您知道我需要做些什么才能使尺寸正确吗?

Any idea what I need to do to get the dimensions correct?

推荐答案

您有2个解决方案.您可以

You have 2 solutions. You can either

(a)分配到新列表newList = lapply(scenbase, function(x) { x[33:152,,drop=F]} )

(b)使用<<-运算符将在lapply(1:length(scenbase), function(x) { scenbase[[x]] <<- scenbase[[x]][33:152,,drop=F]} )位置分配修剪的数据.

(b) use the <<- operator will assign your trimmed data in place lapply(1:length(scenbase), function(x) { scenbase[[x]] <<- scenbase[[x]][33:152,,drop=F]} ).

您的呼叫不起作用,因为i不在全局范围内.您可以通过调用<<-运算符来解决此问题,该运算符将赋值给它在连续的父环境中找到的第一个变量.或通过创建新的修剪列表.

Your call does not work because the i is not in the global scope. You can work your way around that by using calls to the <<- operator which assigns to the first variable it finds in successive parent environments. Or by creating a new trimmed list.

以下是一些复制解决方案(a)的代码:

Here is some code that reproduces solution (a):

listOfDfs = list()
for(i in 1:10) { listOfDfs[[i]] = data.frame("x"=sample(letters,200,replace=T),"y"=sample(letters,200,replace=T)) }
choppedList = lapply(listOfDfs, function(x) { x[33:152,,drop=F]} )

以下是一些复制解决方案(b)的代码:

Here is some code that reproduces solution (b):

listOfDfs = list()
for(i in 1:10) { listOfDfs[[i]] = data.frame("x"=sample(letters,200,replace=T),"y"=sample(letters,200,replace=T)) }
lapply(1:length(listOfDfs), function(x) { listOfDfs[[x]] <<- listOfDfs[[x]][33:152,,drop=F]} )

这篇关于使用lapply子集数据帧中的行-错误的维数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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