【问题标题】:How can I gather_ on all columns but one?我怎样才能在除一列之外的所有列上收集_?
【发布时间】:2017-04-06 10:41:00
【问题描述】:

我需要在数据框的所有列上gather_,除了一个。示例:

# I want to generate a dataframe whose column names are the letters of the alphabet. If you know of a simpler way, let me know!
foo <- as.data.frame(matrix(runif(100), 10, 10))
colnames(foo) <- letters[1:10]

现在,假设我想收集除e 列之外的所有列。这行不通:

mycol <- "e"
foo_melt <- gather_(foo, key = "variable", value = "value", -mycol)
#Error in -mycol : invalid argument to unary operator

这将:

column_list <- colnames(foo)
column_list <- column_list[column_list != mycol]
foo_melt <- gather_(foo, key = "variable", value = "value", column_list)

如果你问我,看起来很复杂。没有更简单的方法吗?

【问题讨论】:

  • 一个选项是setdiff,即gather_(foo, key = "variable", value = "value", setdiff(names(foo), mycol))

标签: r reshape2 tidyr


【解决方案1】:

试试这个:

foo_melt <- gather_(foo, key = "variable", value = "value",names(foo)[-5])

这将为您提供除第 5 列(“e”)之外的所有列。

> head(foo_melt)
          e variable     value
1 0.6359394        a 0.9567835
2 0.1558724        a 0.7778139
3 0.1418696        a 0.2132809
4 0.7184244        a 0.4539194
5 0.4487064        a 0.1049392
6 0.5963304        a 0.8692680

【讨论】:

    【解决方案2】:

    一个选项是one_ofgather

    res1 <- gather(foo, key = "variable", value = "value", -one_of(mycol))
    

    如果我们需要gather_,那么可以使用setdiff

    res2 <- gather_(foo, key = "variable", value = "value", setdiff(names(foo), mycol))
    
    identical(res1, res2)
    #[1] TRUE
    dim(res1)
    #[1] 90  3
    
    head(res1, 3)
    #          e variable     value
    #1 0.8484310        a 0.2730847
    #2 0.0501665        a 0.8129584
    #3 0.6689233        a 0.5457884
    

    【讨论】:

    • 太棒了!我现在什至不需要gather_ - 我使用它是因为要重塑的变量是动态的,但使用one_of 我仍然可以使用gather
    猜你喜欢
    • 2013-07-22
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多