值的滞后,取前一个逻辑值

时间:2015-09-18 05:45:05

标签: r

以下是我在if(isset($_POST['update'])) { $txt = $_POST['txt']; $que= mysql_query("update test set test='$txt' where id='1'"); } $que= mysql_query("select * from test where id=1"); $data=mysql_fetch_array($que); $test = $data[0]; ?> <form method="post" action=""> <input type="text" name="txt" value="<?php echo $test;?>"> <input type="submit" name="update" value="Update"> </form> 列上尝试实现的内容:

whatiwant

使用df1 <- data.frame(value = c(99.99,99.98,99.97,99.96,99.95,99.94, 99.93,99.92,99.91,99.9,99.9,99.9), new_value = c(NA,NA,99.98,NA,99.97,NA, NA,NA,NA,NA,NA,NA), whatiswant = c(99.99,99.96,99.98,99.95,99.97,99.94, 99.93,99.92,99.91,99.9,99.9,99.9)) 字词来解释它应该具有whatiswant的值,对于那些没有new_value的人,它应该采用下一个最低值。

我认为这是一种滞后的东西。这是data.frame:

new_value

编辑:逻辑按以下步骤说明:

  1. 步骤1.如果new_value不是NA,则col3取值。所以第3和第3 排第5行。
  2. 步骤2.第1行col3取col1的值,因为col2是NA。
  3. 步骤3.第二行col3取col1-row4的值,为2nd和3rd col1的行值已在步骤1中使用。
  4. 步骤4.第4行col3取col1-row5的值,如上面的所有行     从col1开始,在前面的步骤中进行。
  5. 步骤5. col3中其余的rows6-12取相同的值 col1-row6-12为col2为NA,而col1-row6-12为non 用于前面的步骤。

1 个答案:

答案 0 :(得分:2)

以功能的形式,评论的每一步,询问是否不清楚:

t1 <- function(df) {
  df[,'whatiswant'] <- df[,'new_value'] # step 1, use value of new_value
  sapply(1:nrow(df),function(row) { # loop on each row
    x <- df[row,] # take the row, just to use a single var instead later
    ret <- unlist(x['whatiswant']) # initial value
    if(is.na(ret)) { # If empty
      if (x['value'] %in% df$whatiswant) { # test if corresponding value is already present
        ret <- df$value[!df$value %in% df$whatiswant][1] # If yes take the first value not present
      } else {
        ret <- unlist(x['value']) # if not take this value
      }
    }
    if(is.na(ret)) ret <- min(df$value) # No value left, take the min
    df$whatiswant[row] <<- ret # update the df from outside sapply so the next presence test is ok.
  })
  return(df) # return the updated df
}

输出:

>df1[,3] <- NA # Set last column to NA
> res <- t1(df1)
> res
   value new_value whatiswant
1  99.99        NA      99.99
2  99.98        NA      99.96
3  99.97     99.98      99.98
4  99.96        NA      99.95
5  99.95     99.97      99.97
6  99.94        NA      99.94
7  99.93        NA      99.93
8  99.92        NA      99.92
9  99.91        NA      99.91
10 99.90        NA      99.90
11 99.90        NA      99.90
12 99.90        NA      99.90
相关问题