Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

I have a dataset with 11 columns with over 1000 rows each. The columns were labeled V1, V2, V11, etc. I replaced the names with something more useful to me using the "c" command. I didn't realize that row 1 also contained labels for each column and my actual data starts on row 2.

Is there a way to delete row 1 and decrement?

2 Answers

0 votes
by
edited by

To delete the first row of a data frame, you can use the negative indices as follows:

data_frame = data_frame[-1,]

To keep labels from your original file, do the following:

data_frame = read.table('data.txt', header = T)

To delete a column:

data_frame$column_name = NULL

For example:

 x = rnorm(10)

 y = runif(10)

df = data.frame( x, y )

df

             x          y

1  -1.74553874 0.24904310

2   0.78970091 0.40401348

3   0.86203201 0.50361443

4  -0.02194766 0.19179475

5   1.07919386 0.70638636

6  -0.23485948 0.41544163

7   0.07170211 0.08740739

8  -2.18997110 0.63813427

9   0.68096662 0.59799302

10  0.05319090 0.13227670

df[-1,] #delete 1st row

             x          y

2   0.78970091 0.40401348

3   0.86203201 0.50361443

4  -0.02194766 0.19179475

5   1.07919386 0.70638636

6  -0.23485948 0.41544163

7   0.07170211 0.08740739

8  -2.18997110 0.63813427

9   0.68096662 0.59799302

10  0.05319090 0.13227670

df$y <- NULL   #delete column “y”

df

             x

1  -1.74553874

2   0.78970091

3   0.86203201

4  -0.02194766

5   1.07919386

6  -0.23485948

7   0.07170211

8  -2.18997110

9   0.68096662

10  0.05319090

If you wish to learn R Programming visit this R Programming Course by Intellipaat.

0 votes
by (3.1k points)

Below are methods to delete first row of data frame in r:
 

  • Method 1: Using Negative Indexing
    You can exclude the first row by using negative indexing:
    sample code:
    df <- data.frame(
    A = c(1, 2, 3),
    B = c("a", "b", "c")
    )

    # Delete the first row
    df <- df[-1, ]

  • Method 2: Using slice() from dplyr
    If you prefer using the dplyr package, you can use the slice() function:
    sample code:
    library(dplyr)

    df <- data.frame(
    A = c(1, 2, 3),
    B = c("a", "b", "c")
    )

    # Delete the first row
    df <- df %>% slice(-1)

     

  • Method 3: Using head()
    Another way is to use the head() function to keep all rows except the first:
    sample code:
    df <- data.frame(
    A = c(1, 2, 3),
    B = c("a", "b", "c")
    )

    # Delete the first row
    df <- head(df, -1)
     

Any of these methods will effectively remove the first row of your dataframe. After executing the code, the variable df will contain the modified dataframe without the first row.

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...