使用 as.numeric(levels(f))[f] 将数据框中的因子子集转换为数字 [英] Converting a subset of factors in a dataframe to numeric using as.numeric(levels(f))[f]
问题描述
我有一个包含 100 个变量的数据框,我想要其中的一个子集,比如说 dataframename[,30:50] 转换为它们的原始数值 (1,2,3,4,5).
I have a dataframe with 100 variables, of which I would like a subset, say dataframename[,30:50] to be converted to their original numeric values (1,2,3,4,5).
我知道我应该在转换因子时使用 as.numeric(levels(f))[f]
,但是我只能在一次转换一个因子时才能使用.我想一次转换它们.
I know that I should use as.numeric(levels(f))[f]
when I convert a factor, but I can only make this work when I convert the factors one at a time. I would like to convert them all at once.
这行不通:
as.numeric(levels(dataframename[,30:50]))[dataframename[,30:50]]
这也不会:
sapply(dataframename[,30:50],as.numeric(levels(dataframename[,30:50]))
[dataframename[,30:50]]
有什么我应该阅读的想法或内容吗?
Any ideas or stuff I should read?
推荐答案
这是一个较小的例子,但这个想法应该成立.您可以使用 lapply
将转换应用于数据框的每一列,然后直接替换这些列.
This is a smaller example but the idea should hold. You can use lapply
to apply your conversion to each column of your data frame and then just replace those columns directly.
# make example data
dat <- as.data.frame(lapply(as.data.frame(matrix(seq(2*3), ncol = 3)), factor))
factorconvert <- function(f){as.numeric(levels(f))[f]}
dat[, 2:3] <- lapply(dat[, 2:3], factorconvert)
dat
# V1 V2 V3
#1 1 3 5
#2 2 4 6
#str(dat)
#'data.frame': 2 obs. of 3 variables:
# $ V1: Factor w/ 2 levels "1","2": 1 2
# $ V2: num 3 4
# $ V3: num 5 6
这篇关于使用 as.numeric(levels(f))[f] 将数据框中的因子子集转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!