Make a new data frame only with specific values in multiple columns

Viewed 47

I wanted to create a new data frame by selecting the available (or desired values) from a data frame from different columns.

So my data is:

df = data.frame(col1 = c("0","0","0","0","0","0"),
                col2 = c("0","0","10","10","0","0"),
                col3 = c("11","11","0","0","0","0"),
                col4 = c("0","0","0","0","12","12"),
                col5 = c("0","0","0","0","0","0"))

> df
  col1 col2 col3 col4 col5
1    0    0   11    0    0
2    0    0   11    0    0
3    0   10    0    0    0
4    0   10    0    0    0
5    0    0    0   12    0
6    0    0    0   12    0

These are characters and I want to create a new data frame by only gathering characters different than "0" in the same order. I have tried different packages but I couldn't find a way to do it effortlessly. So desired output is:

> df.new
  col.new
1      11
2      11
3      10
4      10
5      12
6      12

Thanks in advance!

2 Answers

Here's a base R option using max.col :

new <- df[cbind(seq(nrow(df)), max.col(df != 0))]
data.frame(new)

#  new
#1  11
#2  11
#3  10
#4  10
#5  12
#6  12

This works if you only have one value per row:

library(tidyverse)
df = data.frame(col1 = c(0,0,0,0,0,0),
                col2 = c(0,0,10,10,0,0),
                col3 = c(11,11,0,0,0,0),
                col4 = c(0,0,0,0,12,12),
                col5 = c(0,0,0,0,0,0))
df.new <- df %>%
  summarise(col.new = rowSums(.))

df.new
#>  col.new
#>1      11
#>2      11
#>3      10
#>4      10
#>5      12
#>6      12
Related