我有一个有很多变量的数据集,需要标记它的值。我知道如何将标签一个接一个地添加到它们的值中,但我想加入一个循环,它可以将一个标签自动赋值为1 (1表示某人选择了一个选项,例如,他们有抑郁症,而0表示他们没有选择),这些变量包括dsm_00 (其中1应该被标记为"no could“)、dsm_01 (1表示抑郁)、dsm_02 (1表示焦虑)等等。
我已经创建了一个要分配的名字列表:
labels <- list("no diagnosis", "depression", "anxiety", "bipolar", ....).我有一个密码,一个接一个地去做:
val_lab(mydat$dsm_00) = num_lab("
1 no diagnosis
")我不知道如何将它合并为一个循环(我一直在努力解决这些问题)。任何帮助都将不胜感激!
发布于 2022-05-04 17:54:35
在这种情况下,您可能不想使用循环。一种更简单的方法是编写一个从给定值生成所需标签的函数,并将其应用于整个列。一种方便的方法是dplyr包中的mutate()函数。下面是一个例子:
labels <- list("no diagnosis", "depression", "anxiety", "bipolar")
# This is the function to contain your code for assigning labels
# based on values in your data set. Replace this with whatever
# logic you have. In this example, I've assumed that the values
# we are labeling are all integers we could use to look up labels.
get.label = Vectorize(
function(diagnosis.code) {
labels[[diagnosis.code]]
})
# This package gives you mutate() and %>%
library(dplyr)
# Example data.
data = data.frame(diagnosis.codes = c(1, 3, 2, 2, 1))
# Create a new column "label" by applying your function to the
# values in another column.
data = data %>% mutate(label = get.label(diagnosis.codes))现在,如果您查看您的数据框架,您应该会得到以下内容
> data
# response.codes label
# 1 1 no diagnosis
# 2 3 anxiety
# 3 2 depression
# 4 2 depression
# 5 1 no diagnosishttps://stackoverflow.com/questions/72113080
复制相似问题