user908645
user908645

Reputation: 33

how to get column names in mutate function

everyone! I had a question. In iris dataset, for every row, I wanted to get column names whose value>1, then combine them. The expected result is like this: SL&SW&PL, SL&SW&PL&PW...

library(tidyverse)
data("iris")
colnames(iris)[1:4] <- c("SL","SW","PL","PW") # simplify the colnames
for (i in 1:nrow(iris)) {
  row_i <- iris[i,1:4]
  iris$new_var[i] <- names(row_i)[row_i>2] %>% paste0(.,collapse = "&")
  }

Here are some samples of new_var, and it is the result I expected

> iris$new_var[c(1,30,60,90,120)]
[1] "SL&SW"    "SL&SW"    "SL&SW&PL" "SL&SW&PL" "SL&SW&PL"

However, mutate-function didn't work as I expected.

fournames <- c("SL","SW","PL","PW")
iris %>% mutate(new_var=paste0(fournames[(SL:PW)>2],collapse = "&"))

How to repeat the for-loop result using mutate function?

Upvotes: 2

Views: 225

Answers (1)

user908645
user908645

Reputation: 33

I solved this problem with code:

iris %>% rowwise %>% mutate(new_var=str_c(names(iris)[1:4][c_across(1:4)>2],collapse = "&")) 

Upvotes: 1

Related Questions