官术网_书友最值得收藏!

Editing a data frame in R

Once we have generated a data and converted it into a data frame, we can edit any row or column of a data frame.

How to do it...

We can add or extract any column of a data frame using the dollar ($) symbol, as depicted in the following code:

data = data.frame(x = c(1:4), y = c("tom","jerry","luke","brian"))
data$age = c(2,2,3,5)
data

In the preceding example, we have added a new column called age using the $ operator. Alternatively, we can also add columns and rows using the rbind() and cbind() functions in R as follows:

age = c(2,2,3,5)
data = cbind(data, age)

The cbind and rbind functions can also be used to add columns or rows to an existing matrix.

To remove a column or a row from a matrix or data frame, we can simply use the negative sign before the column or row to be deleted, as follows:

data = data[,-2]

The data[,-2] line will delete the second column from our data.

To re-order the columns of a data frame, we can type the following lines in the R command window:

data = data.frame(x = c(1:4), y = c("tom","jerry","luke","brian"))
data = data[c(2,1)]# will reorder the columns
data

To view the column names of a data frame, we can use the names() function:

names(data)

To rename our column names, we can use the colnames() function:

colnames(data) = c("Number","Names")
主站蜘蛛池模板: 建瓯市| 连州市| 宝丰县| 浪卡子县| 精河县| 于都县| 中阳县| 思茅市| 缙云县| 元阳县| 庆安县| 志丹县| 南阳市| 辛集市| 临颍县| 新绛县| 米易县| 桃园市| 稷山县| 霍山县| 龙井市| 庆阳市| 永新县| 湖北省| 绥宁县| 屏东市| 大余县| 巨野县| 兴业县| 康定县| 昆明市| 昆明市| 南雄市| 灵川县| 惠来县| 宁晋县| 游戏| 江城| 通道| 新绛县| 印江|