My dataframe is of the following form:
Index: Number of pets owned: Age range
10: 30s
2: 50s
4: 60s
6: <20s
9: 70s
etc. Essentially, the number of age ranges are <20s, 20s, 30s, 40s, 50s, 60s, 70s. What I would like to do is turn this categorical age range variable into a continuous one by assigning 1, 2, 3, 4, 5, 6, 7 to the age ranges. Any idea how I can do this in R? I think the as.numeric function could be useful but I've never used it before.
You can do that using as.numeric()
function. Using your dataframe we have:
data_frame <- data.frame(
pets_owned = c("10", "2", "4","6","9"),
age_rank = c("30", "50", "60","20","70")
)
This is your Dataframe looks like:
> data_frame
pets_owned age_rank
1 10 30
2 2 50
3 4 60
4 6 20
5 9 70
Checking the class data type of age_rank column we have:
> class(data_frame$age_rank)
[1] "factor"
So using as.numeric()
:
data_frame[2]=as.numeric(data_frame$age_rank)
# update the value in the position [2] of the dataframe
This is your dataframe with the values 1, 2, 3, 4, 5 in the age rank.
> data_frame
pets_owned age_rank
1 10 2
2 2 3
3 4 4
4 6 1 # note that the value 1
5 9 5 # correspond with the age of 20.
Checking the column again:
> class(data_frame$age_rank)
[1] "numeric"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.