使用`car`跨列重新编码 [英] Using `car` to recode across range of columns
问题描述
我一直在互联网上闲逛,而且不知道如何应用 car
来重新编码一系列列的值。
I've been poking about on the internet, and can't figure out how to apply car
to recode values for a range of columns.
要重新编码单个列的值,我将运行以下命令:
To recode values for a single column, I'd run a command such as:
df$dv_r <- recode(df$dv, "2=1;1=0;0=NA")
然后,如果我想对整个data.frame执行此操作,则可以运行:
And then if I wanted to do this for the whole data.frame, I could run:
df_2 <- lapply(df, FUN = function(x) recode(x, "2=1;1=0;0=NA"))
但是,我不确定如何对一定范围的列执行此操作,例如,在假设的 data.table
称为 df
,我该如何重新编码 20:40
范围内的列的值?
However, I'm not sure how to do this for a range of columns -- for example, in a hypothetical data.table
called df
, how would I recode values for columns ranging from 20:40
?
谢谢!当然,这对于R专家来说超级简单。
Thanks! Sure this is super easy for R experts.
推荐答案
也许还有更多的 data.table
的方法,但这是一种可能性:
Perhaps there is a more data.table
way to do this, but here is one possibility:
library(data.table)
library(car)
## Here is some sample data
set.seed(1)
dt <- data.table(A = sample(0:2, 10, replace = TRUE),
B = sample(0:2, 10, replace = TRUE),
C = sample(0:2, 10, replace = TRUE),
D = rnorm(10), E = rnorm(10), ID = 1:10)
dt
# A B C D E ID
# 1: 0 0 2 -0.04493361 -0.05612874 1
# 2: 1 0 0 -0.01619026 -0.15579551 2
# 3: 1 2 1 0.94383621 -1.47075238 3
# 4: 2 1 0 0.82122120 -0.47815006 4
# 5: 0 2 0 0.59390132 0.41794156 5
# 6: 2 1 1 0.91897737 1.35867955 6
# 7: 2 2 0 0.78213630 -0.10278773 7
# 8: 1 2 1 0.07456498 0.38767161 8
# 9: 1 1 2 -1.98935170 -0.05380504 9
# 10: 0 2 1 0.61982575 -1.37705956 10
使用 .SDcols
定义要将函数应用到哪些列。
Use .SDcols
to define which columns you want to apply the function to.
dt[, 1:3 := lapply(.SD, recode, "2=1;1=0;0=NA"), .SDcols = 1:3]
dt
# A B C D E ID
# 1: NA NA 1 -0.04493361 -0.05612874 1
# 2: 0 NA NA -0.01619026 -0.15579551 2
# 3: 0 1 0 0.94383621 -1.47075238 3
# 4: 1 0 NA 0.82122120 -0.47815006 4
# 5: NA 1 NA 0.59390132 0.41794156 5
# 6: 1 0 0 0.91897737 1.35867955 6
# 7: 1 1 NA 0.78213630 -0.10278773 7
# 8: 0 1 0 0.07456498 0.38767161 8
# 9: 0 0 1 -1.98935170 -0.05380504 9
# 10: NA 1 0 0.61982575 -1.37705956 10
这篇关于使用`car`跨列重新编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!