我需要编写一个条件,说明大数据框的 9 列是否包含以下任一内容:“6%t”(作为每行的前三个字符)、NA 或“”,然后将文件另存为csv。我很难以正确的方式设置条件。目的是确保我保存写入数据帧。
假设 cols 是我需要在数据框中检查的 9 列。
cols -> c("AA", "BB", "SS", "EE"", "OO", "UU", "PP", "QQ", "FF")
if (substring(df[,cols], 1, 3) == "6%t" || is.na(df[,cols]) || df[,cols] == "") {
write.csv(df, file = paste0(path, ".csv"))}
但是,我收到以下错误:
the condition has length > 1
你能帮我解决这个问题吗?
始终在代码中提供一些数据。问题很简单:尺寸错误的条件。 IF 语句必须是
TRUE
或 FALSE
,而不是逻辑向量。看:
#
aux <- sample(c(words, 1000:1999), 17)
aux <- sample(c(aux, "6%tFoo", NA, ""))
aux <- structure(aux, dim = 4:5)
colnames(aux) <- letters[1:5]
a b c d e
[1,] "the" "particular" "consider" "6%tFoo" "1649"
[2,] "1167" "1402" "of" "along" NA
[3,] "question" "" "many" "exercise" "1709"
[4,] "1397" "1152" "oppose" "problem" "1114"
#
substring(aux, 1, 3) == "6%t"
a b c d e
[1,] FALSE FALSE FALSE TRUE FALSE
[2,] FALSE FALSE FALSE FALSE NA
[3,] FALSE FALSE FALSE FALSE FALSE
[4,] FALSE FALSE FALSE FALSE FALSE
您的数据集似乎具有
NA
值,因此请注意它的 substring
行为。试试这个:
#
test <- \(x) any((sapply(x, substring, 1, 3) == "6%t") & !is.na(x)) ||
any(is.na(x)) ||
any(x == "")
#
cols <- "b"
test(aux[, cols])
[1] TRUE
#
cols <- "d"
test(aux[, cols])
[1] TRUE
#
cols <- "e"
test(aux[, cols])
[1] TRUE
#
cols <- c("a", "c")
test(aux[, cols])
[1] FALSE