R中的For循环中的返回函数

时间:2019-09-29 11:54:25

标签: r

我有一个数据框df。我试图执行for循环以返回所有因素的水平。我已经尝试使用以下代码,但未执行

df <- structure(list(ColA = structure(c(19L, 3L, 12L, 21L), .Label = c("asgfg", 
"dds", "dfg", "dfh", "dgh", "dghgd", "dgrert", "dgsh", "dsgdfg", 
"dsgdg", "e", "er", "ewt", "fdg", "fdgd", "fg", "gdfgd", "gdfsh", 
"gf", "gfdg", "gfs", "gh", "ghj", "ghjhg", "gjgj", "gt", "hdsger", 
"hgdhg", "hgj", "hjghj", "jgh", "jyfj", "ret", "rth", "ryuy", 
"sdf", "sdfh", "sfdg", "sgdf", "tyew", "tyu", "tyutyu", "uiuy", 
"yoiy", "yt"), class = "factor"), ColB = structure(c(1L, 1L, 
1L, 1L), .Label = c("A", "B"), class = "factor"), ColC = 1:4, 
  ColD = 2:5), row.names = c(NA, 4L), class = "data.frame"

sa <- names(Filter(is.factor,df))
for (i in sa)
{ res 
res[[i]] <= levels(factor(df[,i]))
return(res) }

我应该得到

res <- 
ColA = "dfg" "er"  "gf"  "gfs"

ColB = "A" 


1 个答案:

答案 0 :(得分:0)

这里正在使用for循环。

sa <- names(Filter(is.factor,df))

res <- list()

for (i in sa)
{
  res[[i]] <- levels(factor(df[,i]))
}
#res
#$ColA
#[1] "dfg" "er"  "gf"  "gfs"

#$ColB
#[1] "A"