问题描述:

I am trying to print a line when my data finds a value that is different than expected. I can check for this, but I cannot figure out how to print the line it was found on, and the values of the variables associated to that specific line.

if(all(Cit1$State1 %in% ValidStates)==TRUE){

cat("Success")} else

{cat("State " State1 "is incorrect.\n")

}

Calling out just the column name (State1 in this case) is a SAS technique. In this case, all I get is an error. Is there an equivalent for this in R?

网友答案:

If you're looking at Cit1$State1 and wanting to check if all values within that column are within the vector ValidStates, and print out the index and values of Cit1 where this is not true, you could do this:

for(i in 1:nrow(Cit1)){
  if( !(Cit1$State1[i] %in% ValidStates) ){
    print(Cit1[i,])
  }
}

A full reproducible answer is found below.

ValidStates <- c("PA", "NY")
names <- c("Philadelphia", "New York", "Chicago")
State1 <- c("PA", "NY", "CH")
Cit1 <- data.frame(names, State1)

for(i in 1:nrow(Cit1)){
  if( !(Cit1$State1[i] %in% ValidStates) ){
    print(Cit1[i,])
  }
}
网友答案:
for( i in 1:length(Cit1$State1))
  if(Cit1$State1[i] %in% lists) print("Success") else print(paste("State",Cit1$State1[i], "is wrong"))
相关阅读:
Top