我正在处理 PDF 的文本层,并且需要进行一些小的更正...
我生成的整洁数据框有一个或两个数据值相差一行。我有错误定位值的“坐标”(由其他变量的组合定义),并且我有它们实际应该去的位置。我只需要将数据值从 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)
}