使用lapply子集数据帧中的行

编程入门 行业动态 更新时间:2024-10-24 21:34:17
本文介绍了使用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子集数据帧中的行

本文发布于:2023-11-04 12:19:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557922.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子集   数据   lapply

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!