How To Remove Rows And Columns Of A Matrix In R

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeHow to remove rows and columns of a matrix in R

Overview

To understand what a matrix is and how to create a matrix in R, read this shot.

Removing rows and columns from an existing matrix

To remove the row(s) and column(s) of a current matrix in R, we use the c() function.

Parameters of the c() function

The numbers that represent the row number and column number we wish to remove are the parameters. For example:

[-c(1), -c(1)]

The code above specifies the first row and the first column.

Code example

mymatrix <- matrix(c("apple", "banana", "cherry", "orange", "mango", "pineapple"), nrow = 3, ncol =2)# removing the first row an first colummn of the matrixmymatrix <- mymatrix[-c(1), -c(1)]mymatrixRun

Code explanation

  • Line 2: We create a 3x2 matrix (a matrix with 3 rows and 2 columns) called mymatrix. We use the matrix() function and pass the parameter values of its shape. nrow = 3 represents 3 rows, while ncol = 2 represents 2 columns.
  • Line 4: Using the c() function, we remove the first row and first column [-c(1), -c(1)] from the matrix.
  • Line 6: We print the modified matrix.

Relevant Answers

Explore Courses

Free Resources

License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)

Tag » How To Remove Rows In R