如何处理data.frame中的因素?

时间:2018-07-16 18:52:51

标签: r dataframe factors

我是R中的新手,我尝试使用数据框进行操作: screen 如何从第10行获取数值数组 ar <-df [10,1]无效

1 个答案:

答案 0 :(得分:0)

您可以使用gsub删除方括号。请参见下面的代码:

# Simulation
x <- factor(c("[1]", "[2,3]", "[4]", "[]"))
str(x)
# Factor w/ 4 levels "[]","[1]","[2,3]",..: 2 3 4 1


foobar <- lapply(x, function(x) {
  # remove brackets
 s <- gsub("\\[||\\]", "", as.character(x)) 
 as.numeric(unlist(strsplit(s, split = ",")))
})

str(foobar)

输出:

List of 4
 $ : num 1
 $ : num [1:2] 2 3
 $ : num 4
 $ : num(0)