Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing columns names using a data frame in r

I have the matrix

m <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE,dimnames = list(c("s1", "s2", "s3"),c("tom", "dick","bob")))

   tom dick bob
s1   1    2   3
s2   4    5   6
s3   7    8   9

#and the data frame

current<-c("tom", "dick","harry","bob")
replacement<-c("x","y","z","b")
df<-data.frame(current,replacement)

  current replacement
1     tom           x
2    dick           y
3   harry           z
4     bob           b

#I need to replace the existing names i.e. df$current with df$replacement if 
#colnames(m) are equal to df$current thereby producing the following matrix


m <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE,dimnames = list(c("s1", "s2", "s3"),c("x", "y","b")))

   x y b
s1 1 2 3
s2 4 5 6
s3 7 8 9

Any advice? Should I use an 'if' loop? Thanks.

like image 376
Elizabeth Avatar asked Jul 17 '12 08:07

Elizabeth


People also ask

How do I change column names in a Dataframe in R?

How to change column headers of a data-frame in R? colnames () function can be used to change the column names of a data-frame column in R. colnames () function can be used for changing one column name at a time, also all the column names can be changed at once.

How do I change multiple column names in a Dataframe in R?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.

How do I change Dataframe column names?

One way of renaming the columns in a Pandas Dataframe is by using the rename() function. This method is quite useful when we need to rename some selected columns because we need to specify information only for the columns which are to be renamed.

How do you replace column values in R?

To replace a column value in R use square bracket notation df[] , By using this you can update values on a single column or on all columns. To refer to a single column use df$column_name .


1 Answers

You can use which to match the colnames from m with the values in df$current. Then, when you have the indices, you can subset the replacement colnames from df$replacement.

colnames(m) = df$replacement[which(df$current %in% colnames(m))]

In the above:

  1. %in% tests for TRUE or FALSE for any matches between the objects being compared.
  2. which(df$current %in% colnames(m)) identifies the indexes (in this case, the row numbers) of the matched names.
  3. df$replacement[...] is the basic way to subset the column df$replacement returning only the rows matched with step 2.
like image 200
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 03 '22 00:11

A5C1D2H2I1M1N2O1R2T1