简体   繁体   English

r遍历列和行

[英]r loop over columns and rows

I'm trying to loop through column[x] in all the rows of a dataframe, using some ifelse condition and updating the value of them. 我试图在数据帧的所有行中循环遍历列[x],使用一些ifelse条件并更新它们的值。 The desired result is a new data frame with the x's values and the updating conditions. 期望的结果是具有x的值和更新条件的新数据帧。 Here is an example: 这是一个例子:

M <- data.frame(x1=c(1,1,1,1), x2=c(1,1.05,1.1,1.15), x3=c(1.15,1,1.14,1),
            y=c(1, 0.90, 0.98, 0.95), z=c(1,1.11,1.02,1.05))

myfun1 <- function(x, y, z) {
  x <- ifelse(x > z, x*y, 1)
  y <- ifelse(x > z, 1, x*y)
  z <- ifelse(x > z, 1, 1/(x*y))
}

M1 <- as.data.frame(lapply(M, function(x) myfun1(x[1:3], x[4], x[5])))

I also tried to vectorize the function, but it dosn't work. 我也试图对该函数进行矢量化,但它不起作用。 Any help? 有帮助吗?

EDIT, this is the expected result 编辑,这是预期的结果

M1 <- data.frame(x1=c(1,1,1,1), x2=c(1,1,1.078,1.093), x3=c(1.15,1,1.14,1),
            y=c(1, 0.945, 1, 1), z=c(1,1.06,1,1))

We can use a for loop 我们可以使用for循环

for(i in 1:3){
   M[,i] <- ifelse(M[,i] > M$z, M[,i]*M$y, 1)
   M$y <- ifelse(M[,i] >M$z, 1, M[,i]*M$y)
   M$z <- ifelse(M[,i] > M$z, 1, 1/(M[,i]*M$y))
}
M

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM