I want to rename some random columns of a large data frame and I want to use the current column names, not the indexes. Column indexes might change if I add or remove columns to the data, so I figure using the existing column names is a more stable solution. This is what I have now:
mydf = merge(df.1, df.2)
colnames(mydf)[which(colnames(mydf) == "MyName.1")] = "MyNewName"
Can I simplify this code, either the original merge()
call or just the second line? "MyName.1"
is actually the result of an xts merge
of two different xts objects.
which
there! R accepts boolean in the operator [].colnames(mydf)[colnames(mydf)=="MyName.1"] = "MyNewName"
should work! – João Danielnames(mydf)[names(mydf) == "MyName.1"] = "MyNewName"
... about 13 or so characters shorter. Although, you may want to replace a vector in that case, use %in% instead of ==. – Brandon Bertelsendata.table
, because this is about data frames (even though data tables are mentioned below). The right way to rename columns in data table is by usingsetnames
– geneorama