[英]How to convert from numeric to factors in R
I have the following dataframe: 我有以下数据框:
df_raw <- cbind( P1=c(1,1,2,2,3), P2=c(2,3,4,4,4) )
How can I convert these numbers to factors with different levels, so that I have something like: 如何将这些数字转换为具有不同水平的因子,以便获得类似的结果:
head(df_factor)
P1 P2
1 "alpha" "beta"
2 "alpha" "gamma"
3 "beta" "delta"
ie where 1 gets converted to "alpha", 2 to "beta", 3 to "gamma" and so on. 也就是说,其中1转换为“ alpha”,2转换为“ beta”,3转换为“ gamma”,依此类推。 I know I could use an
ifelse
statement but this would be more tedious than having some way of just converting the factor levels. 我知道我可以使用
ifelse
语句,但是比起仅转换因子水平的某种方式,这将更加乏味。
If I try for example: 如果我尝试例如:
df$P1 <- factor(df$P1, levels=c("alpha","beta","gamma" ))
I get NAs
for values. 我得到
NAs
的价值。
Firstly, using cbind
gives a matrix
, not a data.frame
- try: 首先,使用
cbind
提供matrix
,而不是data.frame
尝试:
df <- data.frame( P1=c(1,1,2,2,3), P2=c(2,3,4,4,4) )
Then use labels
for your labels instead of levels
, and set levels
to 1:4
to cover all the possible options in df$P1
and df$P2
然后使用
labels
为标签,而不是levels
,并设置levels
,以1:4
,以覆盖所有可能的选择df$P1
和df$P2
df$P1 <- factor(df$P1, levels=1:4, labels=c("alpha","beta","gamma","delta"))
df
# P1 P2
#1 alpha 2
#2 alpha 3
#3 beta 4
#4 beta 4
#5 gamma 4
df$P1
#[1] alpha alpha beta beta gamma
#Levels: alpha beta gamma delta
You could use lapply
to tackle all the variables in one step: 您可以使用
lapply
解决所有变量:
df <- data.frame( P1=c(1,1,2,2,3), P2=c(2,3,4,4,4) )
data.frame(lapply(df,factor,levels=1:4,labels=c("alpha","beta","gamma","delta")))
# P1 P2
#1 alpha beta
#2 alpha gamma
#3 beta delta
#4 beta delta
#5 gamma delta
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.