在for循环中应用if循环的快速方法
这是我的df:在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
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)]