Ben10
Ben10

Reputation: 297

Change the type of a dataframe's column in r?

I am learning r and I have problem with converting the first column of my dataframe to the type like dataset USArrests.

If we view the head dataset of the USArrests:

           Murder Assault UrbanPop Rape
Alabama      13.2     236       58 21.2
Alaska       10.0     263       48 44.5
Arizona       8.1     294       80 31.0
Arkansas      8.8     190       50 19.5
California    9.0     276       91 40.6
Colorado      7.9     204       78 38.7 

To be honest I dont know the type of the first column like: Alabama, Alaska,.... If we used str(USArrests):

'data.frame':   50 obs. of  4 variables:
 $ Murder  : num  13.2 10 8.1 8.8 9 7.9 3.3 5.9 15.4 17.4 ...
 $ Assault : int  236 263 294 190 276 204 110 238 335 211 ...
 $ UrbanPop: int  58 48 80 50 91 78 77 72 80 60 ...
 $ Rape    : num  21.2 44.5 31 19.5 40.6 38.7 11.1 15.8 31.9 25.8 ...

Here is my dataframe:

dat <- data.frame(
  time = factor(c("Breakfast","Lunch","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  total_bill = c(12.7557,14.8,17.23)
)

View it:

1 Breakfast    12.7557
2     Lunch    14.8000
3    Dinner    17.2300

My goal is to convert it just like the USArrest maybe it look like this:

            total_bill
Breakfast    12.7557
Lunch        14.8000
Dinner       17.2300

Any help for this would be much appreciated

Upvotes: 1

Views: 152

Answers (1)

akrun
akrun

Reputation: 887851

We can use column_to_rownames from tibble

library(tibble)
dat1 <- dat %>% 
          column_to_rownames('time')
dat1
#         total_bill
#Breakfast    12.7557
#Lunch        14.8000
#Dinner       17.2300

In base R, we can also do the assignment to row.names and then assign the column to NULL

row.names(dat) <- dat$time
dat$time <- NULL

if we check the dimnames(USArrests), or use row.names, it would be clear that it is the row names

row.names(USArrests)
#[1] "Alabama"        "Alaska"         "Arizona"        "Arkansas"       "California"     "Colorado"      
#[7] "Connecticut"    "Delaware"       "Florida"        "Georgia"        "Hawaii"         "Idaho"         
#[13] "Illinois"       "Indiana"        "Iowa"           "Kansas"         "Kentucky"       "Louisiana"     
#[19] "Maine"          "Maryland"       "Massachusetts"  "Michigan"       "Minnesota"      "Mississippi"   
#[25] "Missouri"       "Montana"        "Nebraska"       "Nevada"         "New Hampshire"  "New Jersey"    
#[31] "New Mexico"     "New York"       "North Carolina" "North Dakota"   "Ohio"           "Oklahoma"      
#[37] "Oregon"         "Pennsylvania"   "Rhode Island"   "South Carolina" "South Dakota"   "Tennessee"     
#[43] "Texas"          "Utah"           "Vermont"        "Virginia"       "Washington"     "West Virginia" 
#[49] "Wisconsin"      "Wyoming"       

Upvotes: 1

Related Questions