将多个虚拟变量收集为 R 中的一个分类变量
Gathering multiple dummy variables as one categorical variable in R
我知道 ,但我很难将其应用于不仅仅是虚拟变量的数据。
加载一些示例代码,主要来自一系列费用
df <- data.frame(Charge = c(12,4,6,10,5,9), Groceries = c(1,0,0,0,0,0),Utilities = c(0,1,0,0,0,0),Consumables = c(0,0,1,0,0,0), Transportation = c(0,0,0,1,0,0),Entertainment = c(0,0,0,0,1,0),Misc = c(0,0,0,0,0,1))
我想创建一个新变量“Category”,它采用当前编码为二进制文件的列名。我可以用 ifelse
做到这一点,但我正在寻找更通用的解决方案,例如从重塑包中出来。
目前,我只能用以下方法解决这个问题:
df$Category <- ifelse(df$Groceries==1, "Groceries",
ifelse(df$Utilities==1,"Utilities",
ifelse(df$Consumables==1,"Consumables",
ifelse(df$Transportation==1,"Transportation",
ifelse(df$Entertainment==1,"Entertainment","Misc")))))
如果总是有一个 1 并且在一行中没有重复,则使用 max.col
到 return 行中最大值的索引,并使用该索引对names
的数据集
df$Category <- names(df)[-1][max.col(df[-1])]
df$Category
#[1] "Groceries" "Utilities" "Consumables" "Transportation" "Entertainment" "Misc"
我知道
加载一些示例代码,主要来自一系列费用
df <- data.frame(Charge = c(12,4,6,10,5,9), Groceries = c(1,0,0,0,0,0),Utilities = c(0,1,0,0,0,0),Consumables = c(0,0,1,0,0,0), Transportation = c(0,0,0,1,0,0),Entertainment = c(0,0,0,0,1,0),Misc = c(0,0,0,0,0,1))
我想创建一个新变量“Category”,它采用当前编码为二进制文件的列名。我可以用 ifelse
做到这一点,但我正在寻找更通用的解决方案,例如从重塑包中出来。
目前,我只能用以下方法解决这个问题:
df$Category <- ifelse(df$Groceries==1, "Groceries",
ifelse(df$Utilities==1,"Utilities",
ifelse(df$Consumables==1,"Consumables",
ifelse(df$Transportation==1,"Transportation",
ifelse(df$Entertainment==1,"Entertainment","Misc")))))
如果总是有一个 1 并且在一行中没有重复,则使用 max.col
到 return 行中最大值的索引,并使用该索引对names
的数据集
df$Category <- names(df)[-1][max.col(df[-1])]
df$Category
#[1] "Groceries" "Utilities" "Consumables" "Transportation" "Entertainment" "Misc"