0
votes

I have a data set as following:-

a <- data.frame(X1="A", X2="B", X3="C", X4="D", X5="0",
                X6="0", X7="0", X8="0", X9="0", X10="0")

Basically it is a 1 row X 10 column data.frame.

The resulting data.frame should have the column elements of a as rows rather than columns. And any columns in a which are equal to "0" should not be present in the new data.frame. For ex. -

#          b
#     [1]  A
#     [2]  B
#     [3]  C
#     [4]  D
3
data.frame(b=a[a!="0"])?user12728748
I have provided an answer to you question below, if that provides a solution please check the accept answer button, if not please clarify the questionrg255

3 Answers

4
votes

Use a transpose and subset with a logical condition

 data.frame("b" = t(df1)[t(df1) != 0])

A second look gave me chance to play with code, you did not need a transpose

data.frame("b" = df1[df1 != 0])
2
votes

You could unlist and then subset

subset(data.frame(b = unlist(a), row.names = NULL), b != 0)

#  b
#1 A
#2 B
#3 C
#4 D
0
votes

Using pivot_longer function, you can reshape your dataframe into a longer format and then filter values that are "0". With the function column_to_rownames from tibble package, you can pass the first column as rownames.

Altogether, you can do something like this:

library(tidyr)
library(dplyr)
library(tibble)


a %>% pivot_longer(everything(), names_to = "Row", values_to = "b") %>%
  filter(b != "0") %>% 
  column_to_rownames("Row")

   b
X1 A
X2 B
X3 C
X4 D