我有几个变量
qual_cols <- c("ExterQual", "ExterCond", "BsmtQual", "BsmtCond", "HeatingQC", "KitchenQual", "FireplaceQu", "GarageQual", "GarageCond", "PoolQC")
每列均由相同的五个chr值组成:
grades <- c( "Po", "Fa", "TA", "Gd", "Ex")
我想数字化
"Po" = 1; "Fa" = 2; "TA" = 4 "Gd" = 6 "Ex" = 11
为了相乘以创建新变量,如下所示:
combi$GarageGrade <- combi$GarageQual * combi$GarageCond
combi$ExterGrade <- combi$ExterQual * combi$ExterCond
combi$KitchenScore <- combi$KitchenAbvGr * combi$KitchenQual
有哪些方法可以实现这一目标?
注意:我是编程的初学者,所以夸大其词是不胜感激的。
示例:
head(combi$ExterQual) # (Gd, TA, Gd, TA, Gd, Ta)
等价于(6,4,6,4,4,6,4)
head(combi$ExterCond) # (TA, TA, TA, TA, TA, TA)
等价于(4,4,4,4,4,4,4)
combi$ExterGrade <- combi$ExterQual * combi$ExterCond
head(combi$ExterGrade) # expected output: (24, 16, 24, 16, 24, 16)
答案 0 :(得分:0)
我们可以使用命名向量将值更改为数字
newdata <- combi[qual_cols]
newdata[] <- lapply(combi[qual_cols], function(x)
setNames(c(1, 2, 4, 6, 11), grades)[x])
nm1 <- grep("(Cond|Qual)$", names(newdata), value = TRUE)
nm2 <- sub("[A-Z][a-z]+$", "", nm1)
nm3 <- paste0(unique(nm2), 'Grade')
newdata[nm3] <- lapply(split.default(newdata[nm1], nm2), function(x) Reduce(`*`, x))
set.seed(24)
combi <- as.data.frame(matrix(sample(grades, 10 * 5, replace = TRUE),
ncol = 10, dimnames = list(NULL, qual_cols)), stringsAsFactors = FALSE)
答案 1 :(得分:0)
如果变量名不一致(即不仅是Qual和Cond),这是一种更灵活的方法:
qual_cols <- c("ExterQual", "ExterCond", "BsmtQual", "BsmtCond", "HeatingQC", "KitchenQual", "FireplaceQu", "GarageQual", "GarageCond", "PoolQC")
numeric_quals = sapply(combi[qual_cols], function(x) ifelse(x == 'Po', 1,
ifelse(x =='Fa', 2,
ifelse(x =='TA', 4,
ifelse(x == 'Gd', 6,
ifelse(x == 'Ex', 11, 0))))) )
combi = combi %>% select(-qual_cols) %>% cbind(numeric_quals)
房子的整体质量
combi$OverallGrade <- combi$OverallQual * combi$OverallCond
head(combi$OverallGrade)
总泳池得分
combi$PoolScore <- combi$PoolArea * combi$PoolQC
整体车库大小
combi$AllGarage <- combi$GarageCars * combi$GarageArea
浴室总数
combi$TotalBath <- combi$BsmtFullBath + (0.5 * combi$BsmtHalfBath) +
combi$FullBath + (0.5 * combi$HalfBath)
房子(包括地下室)的全部完成SF
combi$AllSF <- combi$GrLivArea + combi$TotalBsmtSF
门廊的总SF
combi$AllPorchSF <- combi$OpenPorchSF + combi$EnclosedPorch +
combi$X3SsnPorch + combi$ScreenPorch
组合添加
combi$Additions <- combi$YearRemodAdd + as.numeric(combi$GarageYrBlt)