且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何对列表中所有数据框的列进行复杂的编辑?

更新时间:2023-02-10 13:12:46

您错误地认为for循环中的最后一个命令是有意义的.它不是.实际上,它已被丢弃,因此由于您从未将它分配到任何地方(cbindWaFramesNumeric...的索引),因此它被静默丢弃.

You are mistakenly assuming that the last commmand in a for loop is meaningful. It is not. In fact, it is being discarded, so since you never assigned it anywhere (the cbind and the indexing of WaFramesNumeric...), it is silently discarded.

此外,您在第三个代码块中对data.frame进行了过度索引.首先,它使用data.frame中的i,即使i是data.frames的list中的索引,而不是帧本身.其次(可能是由此引起的),您尝试索引2D框架的三个维度.只需将最后一个索引从[,i,combine]更改为[,combine][combine].

Additionally, you are over-indexing your data.frame in the third code block. First, it's using i within the data.frame, even though i is an index within the list of data.frames, not the frame itself. Second (perhaps caused by this), you are trying to index three dimensions of a 2D frame. Just change the last indexing from [,i,combine] to either [,combine] or [combine].

第三个问题(尽管也许尚未看到)是如果未找到任何内容,match将返回NA.用NA索引框架会返回错误(请尝试mtcars[,NA]查看).我建议您可以用grep替换match:什么都没找到时返回integer(0),在这种情况下就是您想要的.

Third problem (though perhaps not seen yet) is that match will return NA if nothing is found. Indexing a frame with an NA returns an error (try mtcars[,NA] to see). I suggest that you can replace match with grep: it returns integer(0) when nothing is found, which is what you want in this case.

for (i in seq_along(WaFramesNumeric)) {
  f <- which(sapply(WaFramesNumeric[[i]], is.numeric))
  m <- grep("Cost_Center", colnames(WaFramesNumeric[[i]]))
  n <- grep("Device_Name", colnames(WaFramesNumeric[[i]]))
  combine <- c(f,m,n)
  WaFramesNumeric[[i]] <- WaFramesNumeric[[i]][combine]
}