I want to set column names based on the number of columns.
For example,
#iris1 <- iris[,1:4]
if(ncol(iris)==4) colnames(iris) <- c("a","b","c","d")
if(ncol(iris)==5) colnames(iris) <- c("a","b","c","d","e")
I am looking for a way to do that using the dplyr pipeline. Something like this:
iris1 %>%
setNames(ifelse(ncol(.)==4,c("a","b","c","d"),c("a","b","c","d","e")))
UPDATE: akrun's answer gave me this idea which works for me in this particular use-case.
cnames <- c("a","b","c","d","e")
iris1 %>% setNames(cnames[1:ncol(.)])
This solution cannot be generalised. Better solutions are welcome.