Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a prefix to column names

Tags:

dataframe

r

When reading the following helpfile it should be possible to add a prefix to the column names :

colnames(x, do.NULL = TRUE, prefix = "col") 

The following doesn't work for me. What am I doing wrong here?

m2 <- cbind(1,1:4) colnames(m2, do.NULL = FALSE) colnames(m2) <- c("x","Y") colnames(m2) <- colnames(m2, prefix = "Sub_") colnames(m2) 
like image 699
Jonas Tundo Avatar asked Feb 14 '13 09:02

Jonas Tundo


People also ask

How do you add a prefix to a column?

Add Prefix in Excel Using “&” Operator To add the Prefix (Dr.), place the cursor at Column B, type =”Dr. “&A4 and hit the enter key on the keyboard of your computer. Tip: Instead of typing A4 you can type =”Dr. “& > move the cursor to cell A4 and hit the enter key.

How do you add a prefix to a column name in a DataFrame?

The add_prefix() function is used to prefix labels with string prefix. For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed. The string to add before each label.

How do you add a prefix to a column in R?

To add a prefix to columns of an R data frame, we can use paste function to separate the prefix with the original column names.


1 Answers

You have misread the help file. Here's the argument to look at:

do.NULL: logical. If FALSE and names are NULL, names are created.

Notice the and in that description. Your names are no longer NULL, so using prefix won't work.

Instead, use something like this:

> m2 <- cbind(1,1:4) > colnames(m2) <- c("x","Y") > colnames(m2) <- paste("Sub", colnames(m2), sep = "_") > m2      Sub_x Sub_Y [1,]     1     1 [2,]     1     2 [3,]     1     3 [4,]     1     4 
like image 124
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 30 '22 22:10

A5C1D2H2I1M1N2O1R2T1