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?
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),]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With