Kay Lee
Kay Lee

Reputation: 1

To solve the problem of getting factor variable rather than integer after using "row_to_names" in r

series model for predicting yield and putting them into other formulas to generate cash rents forecast.

I want to show the counties' names in the columns and the years in rows in a dataframe.

So I have a vector containing 3 counties' names which all the elements are from other dataframe. I want to put them in all the dataframe and name the columns so I extracted them out. Now I just use an example.

ct_name <- c("Adams","Boone","Champaign")

And I want to combine then with my predicted yield dataframe table.

library(janitor)
table<- matrix(1:6,nrow = 2, ncol = 3, byrow = FALSE)
rownames(table) <- c("2015", "2016")
table <- rbind(ct_name, table)
table <- row_to_names(table, row_number = 1)
table <- data.frame(table)

There was integers in matrix. However, after using row_to_names(), it all becomes factors or logic. How can I solve this problem. I tried is.numeric() and is.integer() but it all failed and I need them to be integer to do the calculations!

How should I do? Thank you guys!

Upvotes: 0

Views: 84

Answers (2)

Michael MacDonald
Michael MacDonald

Reputation: 91

It's unclear why you would use rbind() to add column names as a row in a table, then use row_to_names() to create column names. Once you rbind() a character vector to a matrix of integers it will force all data in the matrix to character. Ronak's answer seems like a good solution.

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389175

Your county names are empty but if you had actual names in them you should do :

colnames(table) <- ct_name

If you want to change the matrix to dataframe just do

table <- data.frame(table)

Also table is a function in R, so it is better if you name your objects with some different name.

Upvotes: 2

Related Questions