2017-10-10 135 views
0

我有一個PDF文本層工作中Elegently重新定位值,並有一些小的修改,使...一個數據幀

我產生的整潔數據框中有一個是關閉一個或兩個數據值一排。我有不正確定位值的「座標」(由其他變量的組合定義),我有他們應該實際去的位置。我只是需要從A移動數據值B和篩選出對應於A.例如該行:

更改此:

data.frame(A = 1:3, 
      B = 1:3, 
      C = c("Oops wrong row", NA, "this one is OK")) 

進入這個:

data.frame(A = 2:3, 
      B = 2:3, 
      C = c("Oops wrong row", "this one is OK")) 

我已經寫了一些代碼實現了這一點。但它似乎比它需要更加冗長。在這個例子中,函數似乎依賴於數據幀的偶然特徵。我認爲這可能是一個共同的任務 - 這種任務是否存在標準模式?或者至少有一個更優雅的方法?

df <- data.frame(A = 1:3, 
       B = 1:3, 
       C = c("Oops wrong row", NA, "this one is OK")) 

get_row <- function(df, A, B, output = "index") { 

    index <- which(df[["A"]] == A & df[["B"]] == B) 

    if (output == "index") { 
    return(index) 
    } 
    else if (output == "C") { 
    return(df[["C"]][[index]]) 
    } 

} 

correct_df <- function(df) { 

    from <- list(A = 1, 
       B = 1) 

    to <- list(A = 2, 
      B = 2) 

    df <- df %>% 
    dplyr::mutate(C = replace(C, 
           get_row(., to[["A"]], to[["B"]]), 
           get_row(., from[["A"]], from[["B"]], 
              output = "C"))) %>% 
    dplyr::filter(A != from[["A"]] | B != from[["B"]]) 

    return(df) 

} 

回答

0

我懷疑你的真實情況可能比你的例子更復雜一點,但是這是種任務的我通常與dplyr::case_when()做。

本質上,如果您有用於定義哪些行需要更改的條件,則可以在case_when()調用中將它們用作邏輯條件。請注意,我創建了一個新變量而不是替換現有變量 - 它使檢查發生的事情變得更容易。

df <- data.frame(A = 1:3, 
      B = 1:3, 
      C = c("Oops wrong row", NA, "this one is OK")) 
df %>% 
    mutate(D = case_when(
    .$C == "Oops wrong row" & !is.na(.$C) ~ .$C[is.na(.$C)], 
    is.na(.$C) ~ .$C[.$C == "Oops wrong row" & !is.na(.$C)], 
    TRUE ~ .$C 
))