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