Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.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
向量化此R循环和自定义函数_R_Loops_Vectorization - Fatal编程技术网

向量化此R循环和自定义函数

向量化此R循环和自定义函数,r,loops,vectorization,R,Loops,Vectorization,我有一个data.frame,在命名列中有分数,我需要根据定义哪些colNames需要分组的索引文件获取某些列簇的rowMeans。我想同时做这件事,因为它目前是在一个循环中完成的,该循环在当前的“集群”中传递以进行工作。见下文 我有两个数据帧,一个是包含以下内容的索引文件(加上更多内容,这只是一个obv示例) 然后,我使用函数通过循环区域来获取区域的行平均值 for (i in seq_along(unique(index$area))){ data[,as.character(uniqu

我有一个
data.frame
,在命名列中有分数,我需要根据定义哪些
colNames
需要分组的索引文件获取某些列簇的
rowMeans
。我想同时做这件事,因为它目前是在一个循环中完成的,该循环在当前的“集群”中传递以进行工作。见下文

我有两个数据帧,一个是包含以下内容的索引文件(加上更多内容,这只是一个obv示例)

然后,我使用函数通过循环区域来获取区域的行平均值

for (i in seq_along(unique(index$area))){
  data[,as.character(unique(index$area))[i]] <- myfun(as.character(unique(index$area))[i])
}
for(沿(唯一(索引$area))的序列中的i){

数据[,as.character(unique(index$area))[i]]我们可以
将“index”中的“name”列按“area”拆分,然后在
列表中循环,根据“index”中的“name”列对“data”进行子集划分,并获得
行平均数

sapply(split(as.character(index$name), index$area), function(x) rowMeans(data[x]))

我们可以
按“区域”拆分“索引”中的“名称”列,然后循环遍历
列表
,根据“索引”中的“名称”列对“数据”进行子集,并获得
行均值

sapply(split(as.character(index$name), index$area), function(x) rowMeans(data[x]))
使用sapply()和
cbind()
如下:

uia <- unique(index$area)
cbind(data, sapply(uia, myfun))
使用sapply()和
cbind()
如下:

uia <- unique(index$area)
cbind(data, sapply(uia, myfun))

请使用
set.seed
使此可复制,因为使用了
sample
。请使用
set.seed
使此可复制,因为使用了
sample
。感谢@akrun,
split
将非常有用,我以前从未遇到过。有什么方法可以操纵o的列名吗该调用中的utput?特别是根据另一个索引对列重新排序,和/或使用
toupper()使colnames大写
?@Alex那么,你需要
循环
通过
拆分的序列,也就是说
l感谢@akrun,
拆分将非常有用,我以前从未遇到过。有没有一种方法可以在该调用中操纵输出的列名?特别是根据另一个索引,和/或使用
toupper()
?@Alex使colnames大写,然后,您需要
通过
拆分的顺序循环
,即
lst
uia <- unique(index$area)
cbind(data, sapply(uia, myfun))
  name1 name2 name3 name4 name5 name6 area1    area2 area4 area5
1     5    10    10     6     8     9   8.2 6.666667     6     8
2     7     9     2     4    10     1   5.6 6.000000     4    10
3     8     1     8     8     4     2   3.4 6.666667     8     4
4     2     4     7     9     5     7   5.0 7.666667     9     5
5     3     7     1    10     1     4   3.8 7.000000    10     1