【问题标题】:Splitting a vector of lists of factors into dataframe with column for each factor level将因子列表向量拆分为具有每个因子级别的列的数据框
【发布时间】:2018-08-16 12:20:45
【问题描述】:

我收到了如下数据:

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
...

【问题讨论】:

  • 请提供可重现的例子:dput(trees$tree_uses[1:6])

标签: r


【解决方案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)
}

也许有人知道一个方便的功能?

【讨论】:

  • 提供可重现的示例数据,我猜您正在寻找“将因子转换为二进制列”。 dput(trees$tree_uses[1:6])
  • 希望现在的数据格式正确。是的,我想要二进制列,但我的数据对于每个观察都有多个因子水平。所以第一步是将数据拆分成单独的因子列。
【解决方案2】:

使用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

【讨论】:

    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 2014-04-12
    • 2014-12-11
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多