我一直在尝试创建一个函数,可以将变量名称传递给将在该函数中创建的data.frame的列名。
例如:
#Create variable
Var1 <- c(1,1,2,2,3,3)
#Create function that dummy codes the variable and renames them
rename_dummies <- function(x){
m <- model.matrix(~factor(x))
colnames(m)[1] <- "Dummy1"
colnames(m)[2] <- "Dummy2"
colnames(m)[3] <- "Dummy3"
m <<- data.frame(m)
}
rename_dummies(Var1)
现在,我可以在这个函数中添加哪些“Var1”会自动放在每个变量名称的“Dummy”前面?理想情况下,我最终会得到3个看起来像这样的变量......
> names(m)
[1] "Var1_Dummy1" "Var1_Dummy2" "Var1_Dummy3"
答案 0 :(得分:4)
尝试以下代码。关键在deparse(substitute)
。我还修改了你的函数,不使用全局赋值运算符<<-
,这是不好的做法。
Var1 <- c(1,1,2,2,3,3)
#Create function that dummy codes the variable and renames them
rename_dummies <- function(x){
nm = deparse(substitute(x))
m <- model.matrix(~factor(x))
colnames(m)[1] <- "Dummy1"
colnames(m)[2] <- "Dummy2"
colnames(m)[3] <- "Dummy3"
m <- data.frame(m)
names(m) <- paste(nm, names(m), sep = "_")
m
}
rename_dummies(Var1)