[英]Is there an R function which converts categorical variables into continuous variables?
我的 dataframe 具有以下形式:
指數:擁有的寵物數量:年齡范圍
10:30秒
2:50秒
4:60年代
6:<20s
9:70年代
等等。基本上,年齡范圍的數量是<20s、20s、30s、40s、50s、60s、70s。 我想做的是通過將 1、2、3、4、5、6、7 分配給年齡范圍,將這個分類年齡范圍變量變成一個連續變量。 知道如何在 R 中做到這一點嗎? 我認為 as.numeric function 可能很有用,但我以前從未使用過它。
你可以使用as.numeric()
function 來做到這一點。 使用您的 dataframe 我們有:
data_frame <- data.frame(
pets_owned = c("10", "2", "4","6","9"),
age_rank = c("30", "50", "60","20","70")
)
這是你的 Dataframe 看起來像:
> data_frame
pets_owned age_rank
1 10 30
2 2 50
3 4 60
4 6 20
5 9 70
檢查 age_rank 列的 class 數據類型,我們有:
> class(data_frame$age_rank)
[1] "factor"
所以使用as.numeric()
:
data_frame[2]=as.numeric(data_frame$age_rank)
# update the value in the position [2] of the dataframe
這是您的 dataframe,年齡等級為 1、2、3、4、5。
> 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.
再次檢查該列:
> class(data_frame$age_rank)
[1] "numeric"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.