-1

I am still new to R and stuck at some trivial things

If i have data is like this:

 "","symbol","len","adjpv"
 "1","HLA-DRB4",5.196415406,0.02376069902
 "2","SCGB1A1",4.269985245,0.01861663475

I need new data to be set to data but without that first annoying column, "", "1", "2"

any help?

I tried newdata = data$symbol$len$adjpv

and newdata = data[ ,"symbol", "len", adjpv"]

data$symbol works but I need to grab all columns except the first one

A.D.
  • 2,352
  • 2
  • 15
  • 25
Dianna
  • 3
  • 4
  • 1
    Your approach works, if you combine the elements in a vector: `data[, c('symbol', 'len', 'adjpv')]`. But in general it might be the rowwnames-column, hence you could just define that using `row.names=1` when reading the data from CSV. – Tino Dec 30 '17 at 11:19

5 Answers5

1

I don't like to use indexes when removing columns from a data.frame I prefer to actually specify their names for readability.

to.remove <- c('column1', 'column2') 
df <- df[, !colnames(df) %in% to.remove] 

I find this approach quite nice.

Sam
  • 644
  • 4
  • 21
1
newData = data[,-1] //removes the first column
Siva Prakash
  • 4,626
  • 34
  • 26
0

Let's say that you dataframe has the df as name.

colnames(df) <- c("firstcolumn","symbol", "len", "adjpv")
df$firstcolumn <- NULL
fugu
  • 6,417
  • 5
  • 40
  • 75
PitterJe
  • 216
  • 2
  • 12
  • Works for dropping single columns but remember that you'll need `list(NULL)` to drop multiple columns. [See here](https://stackoverflow.com/q/19434778/1270695). – A5C1D2H2I1M1N2O1R2T1 Dec 30 '17 at 11:27
  • @A5C1D2H2I1M1N2O1R2T1 thank you for your comment. I though the question is for a simple column and as I wanted to start to learn R better answering question I tried to provide a possible solutin. If it is wrong I can remove the answer. – PitterJe Dec 30 '17 at 11:50
  • No need. Just pointing out that the approach is different if you're trying to remove more than one column at a time. – A5C1D2H2I1M1N2O1R2T1 Dec 30 '17 at 11:50
  • @A5C1D2H2I1M1N2O1R2T1 yes of course. Just to learn what command you will use for multiples. Example `df <- list(NULL)` – PitterJe Dec 30 '17 at 11:52
0

Just remove first col using negation (-):

newdata = data[ ,-1]
Aleksandr
  • 1,814
  • 11
  • 19
0

Using tidyverse approach:

library(tidyverse)
mydf %>%
    select(-1)

If you want to remove the first column, elsewhere you may pass the name of the variable you want to remove.

Scipione Sarlo
  • 1,470
  • 1
  • 17
  • 31