When we have created a data frame in R , for example by reading a csv file from working directory, the first row of the file will be used as the column or variable names of the data frame. Then we can use names() function to rename the variable names as we like. In the following example, a data frame ‘ grade’ is created by reading a csv file from the current working directory, then the variable for test data is renamed as ‘testDate’.
#set the column variable type, then read csv file into a data frame
vartype<-c("character", "character", "character", "character", "character", "numeric","numeric", "numeric","numeric","character")
grade <- read.table("University-NA.csv", colClasses=vartype, header=TRUE, sep=",")
#show the data frame structure
str(grade)
#output
'data.frame': 20 obs. of 10 variables:
$ StudentID: chr "1" "2" "3" "4" ...
$ First : chr "James" "Wilson" "Richard" "Mary" ...
$ Last : chr "Zhang" "Li" "Nuan Ye" "Deng" ...
$ Gender : chr "Male" "Male" "Male" "Female" ...
$ Country : chr "US" "UK" "UK" "US" ...
$ Age : num 23 26 35 21 19 43 37 28 19 25 ...
$ Math : num 73 95 77 60 77 79 87 95 73 66 ...
$ Physics : num 70 999 83 99 89 64 99 87 92 93 ...
$ Chemistry: num 87 83 92 84 93 83 67 93 84 999 ...
$ Date : chr "10/31/08" "03/16/08" "05/22/08" "01/24/09" ...
#to show current variable names
names(grade)
#output
[1] "StudentID" "First" "Last" "Gender" "Country"
[6] "Age" "Math" "Physics" "Chemistry" "Date"
#set new name for 10th column, Date variable
names(grade)[10] <- "testDate"
#show column names again
names(grade)
#output
[1] "StudentID" "First" "Last" "Gender" "Country"
[6] "Age" "Math" "Physics" "Chemistry" "testDate"
#to show first 3 observations
head(grade,3)
#output
StudentID First Last Gender Country Age Math Physics
1 1 James Zhang Male US 23 73 70
2 2 Wilson Li Male UK 26 95 999
3 3 Richard Nuan Ye Male UK 35 77 83
Chemistry testDate
1 87 10/31/08
2 83 03/16/08
3 92 05/22/08
Package ‘plyr’ provides a function rename(), which can just input the old and new value of the column when renaming variables. In the following code example, we rename the columns for Physics and Chemistry of data frame ‘grade’.
# Renaming columns 'Physics' and 'Chemistry'
grade <- rename(grade, c("Physics"="Phy", "Chemistry"="Chem"))
#show data frame first 3 observations
head(grade,3)
#output
StudentID First Last Gender Country Age Math Phy Chem
1 1 James Zhang Male US 23 73 70 87
2 2 Wilson Li Male UK 26 95 999 83
3 3 Richard Nuan Ye Male UK 35 77 83 92
testDate
1 10/31/08
2 03/16/08
3 05/22/08
For getting more knowledge of R, you can watch R tutorial videos on our YouTube channel !
0 Comments