我创建了一个 RMarkdown,用于检查错误。它会输出
我查看了几十个关于列表的 SO 条目,但找不到一个好的答案。下面是我尝试过的内容,我使用此简要示例展示它。该代码可以运行并给出我想要的输出。但它非常冗长,可能很难让我项目团队的其他成员阅读和理解。 简要示例 数据
我得到了以上示例中所有正确的行,但一定有更简单的方法来做到这一点,而且不需要创建
正如您所看到的,不是每一列都具有相同的错误检查。因此,我希望能够很容易地将一个列表添加到
print
语句,指定错误和需要更正的行数(这将检查下面的 df
中的错误)。我创建了另一个数据框(在下面的示例中是 df.index
),用于跟踪每列(在 df
中)需要修正的行。本质上,我需要添加一列来存储需要为 df
中每个列进行纠正的行列表。然后,随着我执行更多的错误检查,我需要将条目附加到 df.index
中给定行中的列表,并在新创建的 summary
数据框中的 rows
列中添加新的列表到其他行。我查看了几十个关于列表的 SO 条目,但找不到一个好的答案。下面是我尝试过的内容,我使用此简要示例展示它。该代码可以运行并给出我想要的输出。但它非常冗长,可能很难让我项目团队的其他成员阅读和理解。 简要示例 数据
library(dplyr)
# Dataframe that contains the dataset that I'm checking for errors.
df <-
structure(
list(
`1.1.` = c("Andrew", "Max", "Sylvia", NA, "1",
NA, NA, "Jason"),
`1.2.` = c(1, 2, 2, NA, NA, 5, 3, NA),
`1.3.` = c(
"cool",
"amazing",
"wonderful",
"okay",
NA,
"sweet",
"chocolate",
"fine"
)
),
class = "data.frame",
row.names = c(NA, -8L)
)
# Dataframe that contains the column numbers and names, which will be used to create a summary of what rows need to be changed for each column.
df.index <-
structure(list(
number = c("1.1.", "1.2.", "1.3."),
name = c("name",
"number", "category")
),
class = "data.frame",
row.names = c(NA, -3L))
我尝试过的方法
obs <- "1.1."
na.index <- which(is.na(df$`1.1.`))
summary <- df.index %>%
dplyr::mutate(rows = ifelse(number == obs, list(na.index), NA))
# Check to see if there are any numeric values in this character column. Adding 6 just to have a duplicate for this example.
na.index2 <-
c(which(!is.na(as.numeric(
as.character(df$`1.1.`)
))), 6)
# Append new list from na.index2 to the existing list in row 1 (or 1.1.), and keep only the unique values, excluding NAs.
summary <- summary %>%
dplyr::mutate(rows = ifelse(number == obs, list(unique(na.omit(
unlist(append(rows, list(na.index2)))
))), NA))
# Column 1.2. in df.
obs <- "1.2."
na.index3 <- which(df$`1.2.` > 2)
summary <- summary %>%
dplyr::mutate(rows = ifelse(number == obs, list(na.index3), rows))
na.index4 <- which(df$`1.2.` == 2)
summary <- summary %>%
dplyr::mutate(rows = ifelse(number == obs, list(unique(na.omit(
unlist(append(rows[2], list(na.index4)))
))), rows))
# Column 1.3. in df.
obs <- "1.3."
na.index5 <- which(df$`1.3.` == "okay")
summary <- summary %>%
dplyr::mutate(rows = ifelse(number == obs, list(na.index5), rows))
输出(也是预期输出)
summary
number name rows
1 1.1. name 4, 6, 7, 5
2 1.2. number 6, 7, 2, 3
3 1.3. category 4
我得到了以上示例中所有正确的行,但一定有更简单的方法来做到这一点,而且不需要创建
obs
并在附加列表时指定行号(例如rows[2]
)。正如您所看到的,不是每一列都具有相同的错误检查。因此,我希望能够很容易地将一个列表添加到
summary
中的rows
列中,就像在每个类别(如1.2.
、1.3.
等)的类似检查中一样,同时能够附加额外的列表(如此处所示)。
x
的参数,例如check_1 <- function(x, y, z)...
。您如何在imap
中传递它们? - AndrewGBall_checks
转换为具有一定结构的嵌套列表,并根据需要取出列表元素。诀窍是如何使用imap
最有效地完成此操作。 - user10917479