您可以定义一个函数来创建您想要的因子,并将其应用于您想要一次使用的数据框的每一列sapply()
。
# some fake data for example
dat <- c("NOT CONDUCTED AT ALL", "RARELY", "OCCASIONALLY", "QUITE FREQUENTLY", "ALWAYS")
df <- data.frame(A=sample(dat, 25, TRUE), B=sample(dat, 25, TRUE), D=rnorm(25))
head(df)
A B D
1 NOT CONDUCTED AT ALL QUITE FREQUENTLY -0.04049165
2 QUITE FREQUENTLY QUITE FREQUENTLY 0.74361906
3 ALWAYS OCCASIONALLY -0.93606555
4 ALWAYS ALWAYS 0.56659322
5 RARELY OCCASIONALLY 0.97216491
6 QUITE FREQUENTLY OCCASIONALLY 0.91125383
# define a function to create a new factor variable
newfac <- function(x, oldval, newval, ordered=TRUE) {
factor(newval[match(x, oldval)], ordered=TRUE)
}
# apply the function to each specified element of the data frame
df[, c("A", "B")] <- sapply(df[, c("A", "B")], newfac,
oldval=c("NOT CONDUCTED AT ALL", "RARELY", "OCCASIONALLY", "QUITE FREQUENTLY", "ALWAYS"),
newval=c("L1", "L1", "L2", "L3", "L4")
)
head(df)
A B D
1 L1 L3 -0.04049165
2 L3 L3 0.74361906
3 L4 L2 -0.93606555
4 L4 L4 0.56659322
5 L1 L2 0.97216491
6 L3 L2 0.91125383