Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编码右路-避免for循环_R_Loops - Fatal编程技术网

编码右路-避免for循环

编码右路-避免for循环,r,loops,R,Loops,我正在浏览我的一个.R文件,通过对它进行一点清理,我试图更加熟悉用R-right的方式编写代码。作为初学者,我最喜欢的出发点之一是摆脱for()循环,并尝试将表达式转换为函数式编程形式。 下面是一个场景: 我正在将一堆数据.帧组合成一个列表,供以后使用 dataList <- list (dataA, dataB, dataC, dataD, da

我正在浏览我的一个.R文件,通过对它进行一点清理,我试图更加熟悉用R-right的方式编写代码。作为初学者,我最喜欢的出发点之一是摆脱
for()
循环,并尝试将表达式转换为函数式编程形式。 下面是一个场景:

我正在将一堆
数据.帧
组合成一个
列表
,供以后使用

dataList <- list (dataA,
                  dataB,
                  dataC,
                  dataD,
                  dataE
                  )
因为我在这里使用的是
列表
,所以我考虑了
lappy
函数。我尝试使用
lappy
函数处理作业,看起来都不错,但只是乍一看。如果我写

f <- function(i, xList) {
  gsub(pattern=c("foo"), replacement=c("baz"), x=colnames(xList[[i]]))
}
lapply(seq(dataList), f, xList=dataList)
我看到没有对初始字符串进行任何更改

那么,如何重写
for()
循环并将其转换为函数式编程形式呢? 如何有效地替换字符串“foo”和“bar”?由于
gsub()
函数只将长度为1的字符向量作为其
模式
参数。

您的代码几乎可以工作——但请记住,R创建了您修改的对象的副本(即传递值语义)。因此,您需要显式地将新字符串分配给colnames,如下所示:

dataA <- dataB <- data.frame(matrix(1:20,ncol=5))
names(dataA) <- c("foo","code","lp15","bar","lh15")
names(dataB) <- c("a","code","lp50","ls50","foo")
dataList <- list(dataA, dataB)
f <- function(i, xList) {
  colnames(xList[[i]]) <- gsub(pattern=c("foo|bar"), replacement=c("baz"), x=colnames(xList[[i]]))
  xList[[i]]
}
dataList <- lapply(seq(dataList), f, xList=dataList)

dataA@Leo谢谢Leo!它工作得很顺利。特别是第二种方法非常优雅,它使索引变得冗余。
lapply (dataList, colnames)
dataA <- dataB <- data.frame(matrix(1:20,ncol=5))
names(dataA) <- c("foo","code","lp15","bar","lh15")
names(dataB) <- c("a","code","lp50","ls50","foo")
dataList <- list(dataA, dataB)
f <- function(i, xList) {
  colnames(xList[[i]]) <- gsub(pattern=c("foo|bar"), replacement=c("baz"), x=colnames(xList[[i]]))
  xList[[i]]
}
dataList <- lapply(seq(dataList), f, xList=dataList)
f <- function(df) {
  colnames(df) <- gsub(pattern=c("foo|bar"), replacement=c("baz"), x=colnames(df))
  df
}
dataList <- lapply(dataList, f)