Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new column with column names

Tags:

r

I have this df:

        A       B   C 
1       NA    100   NA
2      130     NA   NA
3       NA     NA   200
4      110     NA   NA

I'm going to bind them, remove the NA's so i get one single column with their values.

But i need to keep the information from where they came, so i'd like to add a new column with the column_name, so it would come out like this:

      values  column_name 
1       130    A 
2       110    A
3       100    B
4       200    C

Any ideas how to do it?

like image 341
Lucca Ramalho Avatar asked Dec 01 '22 10:12

Lucca Ramalho


1 Answers

This is a job for stack from base R,

s_df <- stack(df)
s_df[complete.cases(s_df),]

which gives,

   values ind
2     130   A
4     110   A
5     100   B
11    200   C

EDIT A one liner version of the above (as per @snoram's comment)

stack(df)[!is.na(df),]
like image 50
Sotos Avatar answered Dec 04 '22 00:12

Sotos