将因子列表的向量分成每个因子级别的带有列的数据框

时间:2018-08-16 12:20:46

标签: r

我收到的数据如下:

tree_uses <- c("Food Fuel Land_benefits Medicines","Food","Food","Food Fuel","Food Fuel","Food")

每个obs的因子在空白处分开。我需要将其转换为df,每个obs有1行,每个“真实”因子水平有1 col。

对于上述数据,它看起来如下:

ID   Food   Fuel  Land_benefits  Medicines ....
1      1      1        1             1
2      1      0        0             0
3      1      0        0             0
4      1      1        0             0
5      1      1        0             0
6      1      0        0             0
...

2 个答案:

答案 0 :(得分:1)

发现了这个作品:

split_factor_cols <- function(x) {
    temp1 <- strsplit(as.character(x)," ")
    factor_names <- unique(unlist(temp1))
    zz <- length(factor_names)
    df <- data.frame(matrix(NA,nrow=length(x),ncol=zz))
    names(df) <- factor_names

    for(i in 1:zz) {
        df[,i] <- unlist(lapply(temp1,function(y) sum(charmatch(factor_names[i],x=y),na.rm=T)))
    }
return(df)
}

也许有人知道便捷的功能?

答案 1 :(得分:0)

使用 tm 软件包:

library(tm)

d <- VCorpus(VectorSource(tree_uses))
dtm <- DocumentTermMatrix(d)

# inspect(dtm)

as.matrix(dtm)
#     Terms
# Docs food fuel land_benefits medicines
#    1    1    1             1         1
#    2    1    0             0         0
#    3    1    0             0         0
#    4    1    1             0         0
#    5    1    1             0         0
#    6    1    0             0         0