Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.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循环中应用if循环的快速方法_R_Performance_If Statement_For Loop - Fatal编程技术网

在for循环中应用if循环的快速方法

在for循环中应用if循环的快速方法,r,performance,if-statement,for-loop,R,Performance,If Statement,For Loop,这是我的df: a <- data.frame(x1 = 1:3, x2 = 0, GF = c("Pelagic", "Demersal", "Cephalopod"), Pelagic = 6, Demersal = 7, Cephalopod = 8) a一种方法是按行使用apply并从该行的GF列中选择列的值 a$x2 <- apply(a, 1, function(x) x[x[["GF"]]]) a # x1 x2 GF Pelagic Demersa

这是我的df:

a <- data.frame(x1 = 1:3, x2 = 0, GF = c("Pelagic", "Demersal", "Cephalopod"), Pelagic = 6, Demersal = 7, Cephalopod = 8)

a一种方法是按行使用
apply
并从该行的
GF
列中选择列的值

a$x2 <- apply(a, 1, function(x) x[x[["GF"]]])
a
#  x1 x2         GF Pelagic Demersal Cephalopod
#1  1  6    Pelagic       6        7          8
#2  2  7   Demersal       6        7          8
#3  3  8 Cephalopod       6        7          8

a$x2那么您想从每行中选择不同的列?您可以使用数字矩阵从data.frame中进行复杂的提取。下面是它的工作原理

a$x2 <- a[cbind(1:nrow(a), match(GF_list, names(a)))]

a$x2以下是一个给出数值结果的解决方案:

i <- 1:nrow(a)
j <- which(a$GF %in% GF_list)
as.matrix(a[,(ncol(a)-length(GF_list)+1):ncol(a)])[cbind(i,j)]

i@Loulou这应该是最快的复制方式
a$x2 <- a[cbind(1:nrow(a), match(GF_list, names(a)))]
i <- 1:nrow(a)
j <- which(a$GF %in% GF_list)
as.matrix(a[,(ncol(a)-length(GF_list)+1):ncol(a)])[cbind(i,j)]