【问题标题】:Taking variable names out of column and creating a new column value based on condition从列中取出变量名并根据条件创建新的列值
【发布时间】:2021-12-27 18:29:49
【问题描述】:

我有这个矩阵 df,第一列中包含所有单词,第 2-75 列中包含单词所属的不同 LIWC 类别。

这是我所拥有的玩具示例:

word posemo certain insight
certainly 1 0 1
obviously 1 1 1
sure 1 0 0
directly 1 0 1
insight 1 1 0
guarantee 0 1 0
prove 1 0 1

这就是我想要实现的目标:

word posemo certain insight Categories
certainly 1 0 1 posemo, insight
obviously 1 1 1 posemo, certain, insight
sure 1 0 0 posemo
directly 1 0 1 posemo,insight
insight 1 1 0 posemo, certain
guarantee 0 1 0 certain
prove 1 0 1 posemo, insight

我一直在查看 stackoverflow,但似乎找不到适用于我正在尝试做的事情的东西。这个Taking variable names out of column and creating new columns in R 很接近,但不处理条件。

有什么建议吗?提前致谢

【问题讨论】:

    标签: r matrix dplyr


    【解决方案1】:

    尝试使用apply

    data.frame( dat, Categories=t(
       t( apply( dat[,2:4], 1, function(x) colnames(dat[,2:4])[as.logical(x)] ) ) ))
    
           word posemo certain insight               Categories
    1 certainly      1       0       1          posemo, insight
    2 obviously      1       1       1 posemo, certain, insight
    3      sure      1       0       0                   posemo
    4  directly      1       0       1          posemo, insight
    5   insight      1       1       0          posemo, certain
    6 guarantee      0       1       0                  certain
    7     prove      1       0       1          posemo, insight
    

    数据

    dat <- structure(list(word = c("certainly", "obviously", "sure", "directly", 
    "insight", "guarantee", "prove"), posemo = c(1L, 1L, 1L, 1L, 
    1L, 0L, 1L), certain = c(0L, 1L, 0L, 0L, 1L, 1L, 0L), insight = c(1L, 
    1L, 0L, 1L, 0L, 0L, 1L)), class = "data.frame", row.names = c(NA, 
    -7L))
    

    编辑速度,尝试预定义关键数据

    n <- colnames( dat[,2:4] )
    lo <- dat[,2:4] == 1
    
    data.frame( dat, Categories=t(t( apply( lo, 1, function(x) n[x] ) ) ))
    

    【讨论】:

    • 谢谢,这真的很棒!这适用于玩具示例,但需要永远加载具有 60.000 行的整个 df。幸好我今天有时间:)
    【解决方案2】:

    这就是诀窍:

    遍历行并找出哪些行等于 1 (cols &lt;- x[i,] == 1),然后获取这些列名 (cats &lt;- na.omit(colnames(x)[cols])),然后将它们作为单个字符串粘贴在一起并替换 categories 的值 (x$categories[i] &lt;- paste(cats, collapse = ", ") )

    x <- tibble(word = c("love","hate","sad"),
                happy = c(1,0,0),
                sad = c(0,1,1),
                emotion = c(1,1,1),
                categories = c(NA,NA,NA))
    
    for(i in 1:nrow(x)){
      cols <- x[i,] == 1
      cats <- na.omit(colnames(x)[cols])
      x$categories[i] <- paste(cats, collapse = ", ")
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      相关资源
      最近更新 更多