Helene
Helene

Reputation: 959

Generate warning in R for more than one items

I have a question about generating warnings for more than one items at a time in R. Please refer to the following dataframe and codes:

Dataframe dat:

  inputs var1 var2
A    1    a    1
B    2    b    3
B    3    b   NA
C    4    d   NA
C    5    e    4

if (any(duplicated(dat$inputs))==T){
  warning(paste("The following inputs: ", dat$inputs[duplicated(dat$inputs)],"is duplicated.",sep=""))
}

As you can see both B and C will be shown in the warning, like:

Warning message:
The following inputs: B is duplicated.The following inputs: C is duplicated.

I'm okay with such warning message output, but it is not ideal. Is there a way to combine the two sentences and make it look like:

Warning message:
The following inputs: B,C are duplicated.

Thanks a lot in advance for your attention and time.

Helene

Upvotes: 0

Views: 66

Answers (1)

Vlo
Vlo

Reputation: 3188

I couldn't get your code to run, so I made up some/modified your code/data.

dat = read.table(text = "
inputs var1 var2 var3
A    1    a    1
B    2    b    3
B    3    b   NA
C    4    d   NA
C    5    e    4", header = T)


if (any(b<-duplicated(dat$inputs))){
  if (length(c<-unique(dat$inputs[b]))>1) {warning(paste0("The following inputs: ", paste0(c, collapse=", "), " are duplicated."))} else
  {warning(paste0("The following input: ", paste0(c, collapse=", "), " is duplicated."))}
}


Warning message:
The following inputs: B, C are duplicated. 

Single duplicate

dat = read.table(text = "
inputs var1 var2 var3
A    1    a    1
A    2    b    3
E    3    b   NA
C    4    d   NA
G    5    e    4", header = T)

Warning message:
The following input: A is duplicated. 

Upvotes: 1

Related Questions