这个问题与我问R: Using Apply Function to clean likert answers
的问题有些相关我有一个比喻尺,但一切都是文字。我希望将列转换为因子,然后转换为数字。答案中缺少值
df[,104:123] <- as.numeric(apply(df[,104:105], 2,
function (x) factor(x,levels = c("NEVER","RARELY","SOMETIMES","MOST OF THE TIME","ALWAYS"))))
但是我收到以下错误:Warning message:
NAs introduced by coercion
实际上它已将所有内容转换为NA
我在没有as.numeric
转换的情况下运行代码,看起来没问题
以下是两列的输出
apply(df[,104:123], 2, function(x) unique(x))
$Ans.1
[1] "" "SOMETIMES" "MOST OF THE TIME" "RARELY" "ALWAYS" "NEVER"
$Ans.2.
[1] "" "SOMETIMES" "MOST OF THE TIME" "RARELY" "ALWAYS" "NEVER"
任何人都可以在我的代码中看到问题
谢谢
答案 0 :(得分:2)
我们需要使用Property="Button.IsFocused" Value="True"
代替lapply
,因为应用返回apply
而matrix
只能有一个类。因此,如果有任何元素是matrix
,那么它将是factor
类,而不是character
。通过在character
课程上使用as.numeric
,我们可以获得所有NAs。
character
答案 1 :(得分:0)
您能提供一些可重现的数据吗?
另外,请参阅我to_value
的{{1}}示例,该示例可能对您有用:
x <- factor(c("ALWAYS", "SOMETIMES", "NEVER","RARELY","SOMETIMES","SOMETIMES", "MOST OF THE TIME","ALWAYS", "SOMETIMES"),
levels = c("NEVER","RARELY","SOMETIMES","MOST OF THE TIME","ALWAYS"))
table(x)
> NEVER RARELY SOMETIMES MOST OF THE TIME ALWAYS
> 1 1 4 1 2
table(sjmisc::to_value(x))
> 1 2 3 4 5
> 1 1 4 1 2
您还可以提供数据框作为参数:
df[,104:105] <- to_value(df[,104:105])