2017-10-10 138 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 
))