Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exclude more than one column when using the function pivot_longer()? [duplicate]

Tags:

r

tidyr

I'm trying to exclude all 3 columns

billboard %>% 
  pivot_longer(-artist,-track,-date.entered , names_to = "Week Spent", values_to ="freq",values_drop_na = TRUE)
like image 414
sovajuice Avatar asked Mar 24 '26 21:03

sovajuice


1 Answers

According to ?pivot_longer, the cols can take any of the select-helpers functions if we want to specify substring of column names or can use c() with either quoted or unquoted full column names.

Tidyverse selections implement a dialect of R where operators make it easy to select variables:

: for selecting a range of consecutive variables. ! for taking the complement of a set of variables. & and | for selecting the intersection or the union of two sets of variables. c() for combining selections.


As a reproducible example

library(dplyr)
library(tidyr)
mtcars %>%
    pivot_longer(cols = -c(vs, am, disp, gear,  carb))
# A tibble: 192 x 7
#    disp    vs    am  gear  carb name   value
#   <dbl> <dbl> <dbl> <dbl> <dbl> <chr>  <dbl>
# 1   160     0     1     4     4 mpg    21   
# 2   160     0     1     4     4 cyl     6   
# 3   160     0     1     4     4 hp    110   
3 4   160     0     1     4     4 drat    3.9 
# 5   160     0     1     4     4 wt      2.62
# 6   160     0     1     4     4 qsec   16.46
# 7   160     0     1     4     4 mpg    21   
# 8   160     0     1     4     4 cyl     6   
# 9   160     0     1     4     4 hp    110   
#10   160     0     1     4     4 drat    3.9 
like image 161
akrun Avatar answered Mar 27 '26 12:03

akrun