-2

抱歉问了另一个问题,但我彻底搜索并没有找到令人满意的答案。

我得到了一个data.frame包含 6 列的子集,它们都factors包含 5 个级别的李克特量表数据:

strongly disagree - disagree - neutral - agree - strongly agree 

问题是,它们的排序不正确并且在一种情况下缺少一个级别。所以我知道如何分别更正列的顺序:

data_frame$somecolumn <- 
ordered(data_frame$somecolumn, levels = c("strdisag", "disagree",  "neutral","agree","stragree"))

我的问题是如何替换:data_frame$somecolumn用一个会影响所有列的表达式,data.frame而不仅仅是一个变量。

4

1 回答 1

1

我想你的意思是这样的......

# Make some reproducible data
set.seed(123)
df <- data.frame( replicate( 6 , sample( c("strdisag", "disagree",  "neutral","agree","stragree") , 5 , repl = TRUE ) ) )

#  Unordered factor variable
df[,1]
[1] disagree agree    neutral  stragree stragree
Levels: agree disagree neutral stragree

# Make list of ordered factor variables
out <- lapply( df , function(x) ordered(x, levels = c("strdisag", "disagree",  "neutral","agree","stragree") ) )

#  Combine into data.frame
res <- do.call( data.frame , out )
        X1       X2       X3       X4       X5       X6
1 disagree strdisag stragree stragree stragree    agree
2    agree  neutral  neutral disagree    agree  neutral
3  neutral stragree    agree strdisag    agree  neutral
4 stragree  neutral  neutral disagree stragree disagree
5 stragree  neutral strdisag stragree    agree strdisag

#  Check result
res[,1]
[1] disagree agree    neutral  stragree stragree
Levels: strdisag < disagree < neutral < agree < stragree
于 2013-08-20T16:14:08.427 回答