gpt4 book ai didi

r - 我怎样才能在除一列之外的所有列上收集_?

转载 作者:行者123 更新时间:2023-12-02 05:42:36 26 4
gpt4 key购买 nike

我需要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)

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

最佳答案

一个选项是 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

关于r - 我怎样才能在除一列之外的所有列上收集_?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40747226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com