我有一个创建检查列的函数,如果有值,则使用字符串,而NA则使用其他字符串。我想在一个表上运行此功能,但是我不知道如何操作。 另外,当前函数需要使用colnames参数作为“”,是否可以像tidyverse函数那样使用非“”?
我尝试使用apply
,但是它怎么知道姓氏呢?我想拥有一个可以在每一列上运行的函数,否则就不可能采用向量的colnames。
library(dplyr)
# Use mtcars dataset
cars = datasets::mtcars
# Add some NA
cars[1, 5] <- NA
cars[2, 4] <- NA
# Create Function
create_check = function(x , y){
names = as.character(y)
name_col <- paste0(names, "error")
mutate(x, name_col = ifelse(is.na(get(names)), paste0(names," is wrong"), "NA" ))
}
输出应该是一个新列,其中包含NA或字符串(例如“ drat isrong”),因此,如果有10列,则会创建10个新列。新的colname应该是要在其上搜索NA的列的名称以及单词“ error”。
hp drat wt qsec vs am gear carb hp error drat error ...
1 110 NA 2.620 16.46 0 1 4 4 NA drat is wrong
2 NA 3.90 2.875 17.02 0 1 4 4 hp is wrong NA
3 93 3.85 2.320 18.61 1 1 4 1 NA NA
请帮助?
答案 0 :(得分:0)
您可以使用anyNA
检查一列是否具有NA值。要将其应用于您的数据集
cars = datasets::mtcars
# Add some NA
cars[1, 5] <- NA
cars[2, 4] <- NA
out <- lapply(cars, anyNA)
向量out
具有其NA列的子集。 cars数据框是整齐的数据,其中每一行都对应于一辆车,因此,您当然不能仅仅粘贴一个向量,该向量指向哪些变量具有NA。如果您想使用粘贴命令,则可以执行以下操作:
ifelse(names(cars) %in% names(cars)[out == TRUE], paste0(names(cars), " is wrong"), "NA" )