将因子水平应用于缺少因子水平的多个列

时间:2018-01-10 21:16:57

标签: r multiple-columns lapply

我有一个包含许多因素的数据框,并希望创建显示每个因子分布的统计表,包括零观察的因子水平。例如,这些数据:

structure(list(engag11 = structure(c(5L, 4L, 4L), .Label = c("Strongly Disagree", "Disagree", "Neither A or D", "Agree", "Strongly Agree"), class = "factor"), encor11 = structure(c(1L, 1L, 1L), .Label = c("Agree", "Neither Agree or Disagree", "Strongly Agree"), class = "factor"), know11 = structure(c(3L, 
1L, 1L), .Label = c("Agree", "Neither Agree or Disagree", "Strongly Agree"), class = "factor")), .Names = c("engag11", "encor11", "know11"), row.names = c(NA, 3L), class = "data.frame")

显示6行,但每列只观察到一些因子水平。当我制作一张桌子时,我不仅要显示观察到的水平的计数,还要显示未观察到的水平(例如“非常不同意”)。像这样:

# define the factor and levels
library(dplyr);library(pander);library(forcats)
eLevels<-factor(c(1,2,3,4,5), levels=1:5, labels=c("Strongly    Disagree","Disagree","Neither A or D","Agree","Strongly Agree"),ordered =TRUE )

# apply the factor to one variable
csc2$engag11<-factor(csc2$engag11,eLevels)

t1<-table(csc2$engag11)
pander(t1)

这导致频率表显示每个级别的计数,包括未报告/观察到的级别的零。

但我有几十个要转换的变量。 Stackoverflow上推荐的简单lapply函数似乎不起作用,例如:

csc2[1:3]<-lapply(csc[1:3],eLevels)

我也为此尝试了一个简单的函数(n =列列表),但失败了:

facConv<-function(df,n)
{   df$n<-factor(c(1,2,3,4,5), levels=1:5, labels=c("Strongly 
Disagree","Disagree","Neither A or D","Agree","Strongly Agree") )
return(result)   }

有人可以提供解决方案吗?

2 个答案:

答案 0 :(得分:1)

lapply应该可以正常工作,您只需要指定factor()函数:

csc2[1:3] <- lapply(csc2[1:3], function(x) factor(x, eLevels))

然后你可以调用像:

这样的表
table(csc2[1])

#Strongly    Disagree             Disagree       Neither A or D                Agree       Strongly Agree 
#                   0                    0                    0                    2                    1 
table(csc2[2])

#Strongly    Disagree             Disagree       Neither A or D                Agree       Strongly Agree 
#                   0                    0                    0                    3                    0 

答案 1 :(得分:0)

优雅而快捷的方法是使用for循环:

df <- data.frame(A = c("A", "A", "B"),
                 B = c("A", "C", "A"),
                 C = c("A", "A", "D"))
lvl <- c("A", "B", "C", "D", "E")

for (i in 1:ncol(df)) {
  df[,i] <- factor(df[,i], levels=lvl)
}

table(df$A)

如果您的原始数据是数字,那么:

df <- data.frame(A = c(1,1,2),
                 B = c(1,3,1),
                 C = c(1,1,4))
lvl <- c("A", "B", "C", "D", "E")
for (i in 1:ncol(df)) {
  df[,i] <- factor(df[,i], levels=1:5, labels=lvl)
}
df
table(df$A)