Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

dplyr - Is there a way to turn a specific amount of columns to rows in R?

A B C n n%
FALSE FALSE FALSE randomnum1 0.86
FALSE FALSE TRUE randomnum2 0.6
FALSE TRUE FALSE randomnum3 0.3
TRUE FALSE FALSE randomnum4 0.84
question from:https://stackoverflow.com/questions/65902741/is-there-a-way-to-turn-a-specific-amount-of-columns-to-rows-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This might be not the most efficient way, but it does the job.

Note: your "n%" column does not have a proper R column name so I chose "n_pct" instead.

df <- data.frame(A = c(F, F, F, T),
                 B = c(F, F, T, F),
                 C = c(F, T, F, F),
                 n = c(1, 2, 3, 4),
                 n_pct = c(0.86, 0.6, 0.3, 0.84))

library(tidyverse)
df %>%
  pivot_longer(cols = c(A, B, C)) %>%
  group_by(n) %>%
  mutate(sum_value = sum(value),
         name      = if_else(sum_value == 0, "---", name),
         helper    = 1:n()) %>%
  ungroup() %>%
  filter(value == TRUE | (sum_value == 0 & helper == 1)) %>%
  select(name, n, n_pct)

which gives:

# A tibble: 4 x 3
  name      n n_pct
  <chr> <dbl> <dbl>
1 ---       1  0.86
2 C         2  0.6 
3 B         3  0.3 
4 A         4  0.84

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...