0

I want to create a new variable with the value of column number in my DF by its name. I have managed to do this:

firstCol <- which(colnames(Mydf) == "Cars")

It takes the column number of the column with the name "Cars" and set its number to the object firstCol. It works well and good on base.

latly, I've been using dplyr and pipes and I'm trying to create a variable and do the same thing by using pipes but I'm unable to do this - use this line but in pipes %>% Can you help me? thanks, Ido

Ido
  • 201
  • 1
  • 8
  • Hi, Can you ```dput()``` some data will be helpfult to help. ```firstCol <- subset(DF,DF$Mydf == 'Cars')``` is that something you want? – Tushar Lad Aug 10 '20 at 11:18
  • hey! thank you but I dont really understanrd, this line works perfect: firstCol <- which(colnames(Mydf) == "Cars") but how do I use it in pipes? >%> firstCol <- which(colnames(Mydf) == "Cars") >%> is not working – Ido Aug 10 '20 at 11:41
  • you can try ```firstCol <- Mydf %>% select(Cars)``` – Tushar Lad Aug 10 '20 at 11:45
  • this one create a df with a column. the thing I want is to get the index of the column into a new variable at the global env. (the result is a new variable called firstcol and has the value 17 for example) – Ido Aug 10 '20 at 11:52
  • Refre this link https://stackoverflow.com/questions/38474882/r-further-subset-a-selection-using-the-pipe-and-placeholder. hope this will help as answer could be duplicate if it is already available. – Tushar Lad Aug 10 '20 at 11:58

1 Answers1

0

The dplyr way to do this is select.

Here is an example using some made up data:

df <- data.frame(cars = sample(LETTERS, 100, replace = TRUE),
                 mpg = runif(100, 15, 45),
                 color = sample(c("green", "red","blue", "silver"), 
                                100, replace = TRUE)) %>% tibbble()  
df %>% select(cars)
# A tibble: 100 x 1
   cars 
   <chr>
 1 R    
 2 V    
 3 I    
 4 Q    
 5 P    
 6 D    
 7 J    
 8 Q    
 9 R    
10 A    
# ... with 90 more rows

You can also remove columns with select(-col_name)

df %>% select(-mpg)
# A tibble: 100 x 2
   cars  color 
   <chr> <chr> 
 1 R     blue  
 2 V     silver
 3 I     red   
 4 Q     green 
 5 P     silver
 6 D     silver
 7 J     green 
 8 Q     blue  
 9 R     red   
10 A     silver
# ... with 90 more rows
Ben Norris
  • 5,639
  • 2
  • 6
  • 15