Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201945

Set column names conditionally using dplyr

$
0
0

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.


Viewing all articles
Browse latest Browse all 201945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>