I'm using as.data.frame()
function to turn a table into dataframe in R, and I would like to set column names with the function.
I found that there's an optional argument for as.data.frame(),
which is col.names
.
The documentation says that it's a character vector of column names. However, whatever I put in col.names
, the result keeps the same.
x = c('a','b','c','a')
x_table = table(x)
x_df = as.data.frame(x_table, col.names = c('name', 'freq'))
Output here is:
x Freq
1 a 2
2 b 1
3 c 1
I understand I could use colnames(df)
to change the column names after the dataframe is created, but I really wonder why col.names
does not work here.
Thank you.
Duplicate column names are allowed, but you need to use check. names = FALSE for data. frame to generate such a data frame. However, not all operations on data frames will preserve duplicated column names: for example matrix-like subsetting will force column names in the result to be unique.
The easiest way to remove repeated column names from a data frame is by using the duplicated() function. This function (together with the colnames() function) indicates for each column name if it appears more than once. Using this information and square brackets one can easily remove the duplicate column names.
colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.
Use the duplicated() function to create a vector that indicates which columns are identical. Optionall, show the names of the duplicated columns using the colnames() function. Remove the duplicated columns with the square brackets [] and the !- symbol.
If you want to avoid assigning the column names after creating the dataframe, you can utilize the dnn
parameter in the table
function to specify your "name" column, and the responseName
parameter in the as.data.frame
function to specify the "freq" column.
x <- c('a','b','c','a')
x_df <- as.data.frame(table(x, dnn = list("name")), responseName = "freq")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With