Saving a large number of columns when using

I have a very wide df (85 columns) which I want to convert to long format using gather. Instead of using the syntax -c(all the columns I do not want to gather)to save columns, I created an object with column names and I get an error.

Error in -c(KeepThese) : invalid argument to unary operator

For example, using iriswith a few additional fields

require(tidyr)
iris$Season <- sample(c("AAA", "BBB"), nrow(iris), replace = T)
iris$Var <- sample(c("CCC", "DDD"), nrow(iris), replace = T)

> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species Season Var
1          5.1         3.5          1.4         0.2  setosa    AAA DDD
2          4.9         3.0          1.4         0.2  setosa    AAA CCC
3          4.7         3.2          1.3         0.2  setosa    BBB CCC
4          4.6         3.1          1.5         0.2  setosa    BBB CCC
5          5.0         3.6          1.4         0.2  setosa    BBB DDD
6          5.4         3.9          1.7         0.4  setosa    AAA DDD

I want to collect all the columns except 5: 7, which are made into the object below.

KeepThese <- colnames(iris)[5:7]

Now I want gatherall the columns except 5: 7 and call the ID column and the numeric field Value and use the following code and get an error.

dat <- iris %>% gather(Part, Value, -c(KeepThese))


Error in -c(KeepNames) : invalid argument to unary operator

How can I specify a bunch of columns that I do not want to collect without writing each of them to tidyr?

APPENDIX Why does my code not work?

+4
3

: , one_of() - , .

dat <- iris %>% gather(Part, Value, -one_of(KeepThese))

:

- as.name(). , . do.call(c, ...), gather().

dat <- iris %>% gather(Part, Value, -do.call("c", lapply(KeepThese, as.name)))
head(dat)
#   Species Season Var         Part Value
# 1  setosa    AAA CCC Sepal.Length   5.1
# 2  setosa    AAA CCC Sepal.Length   4.9
# 3  setosa    AAA DDD Sepal.Length   4.7
# 4  setosa    AAA CCC Sepal.Length   4.6
# 5  setosa    AAA CCC Sepal.Length   5.0
# 6  setosa    AAA DDD Sepal.Length   5.4

%in% which() ( jbaums).

iris %>% gather(Part, Value, -which(names(.) %in% KeepThese))
+5

match ( gather ):

dat <- iris %>% gather(Part, Value, -(match(KeepThese, colnames(.))))
head(dat)

##   Species Season Var         Part Value
## 1  setosa    BBB DDD Sepal.Length   5.1
## 2  setosa    AAA CCC Sepal.Length   4.9
## 3  setosa    BBB CCC Sepal.Length   4.7
## 4  setosa    AAA CCC Sepal.Length   4.6
## 5  setosa    BBB DDD Sepal.Length   5.0
## 6  setosa    BBB CCC Sepal.Length   5.4
+2

-matches

dat <- iris %>% gather(Part, Value, -matches(paste(KeepThese, collapse="|")))
+1

Source: https://habr.com/ru/post/1623482/


All Articles