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)
}