how to write R function to find row names into column name and extract value?

Hi Everyone,

I am a beginner in R.

I have two data frames and want to extract values where row names matches with coll names.

Can i use match function?

## dataframe 1 has 5 observations and its 5 element    
df = data.frame(x = c("P1","P2","P3","P4","P5"), 
                f_1 = c("NA","1","NA","NA","NA"), 
                f_2= c("NA","1","NA","NA","NA"),
                f_3= c("1","7","NA","NA","NA"),
                f_4= c("NA","NA","5","NA","NA"),
                f_5= c("NA","NA","2","NA","NA"),
                stringsAsFactors = FALSE)

## Dataframe 2 has 5 observations and their allias.
df2 = data.frame(x = c("D1","D2","D3","D4","D5"),
                 f=c("f_1","f_20","f_30","f_4","f_15"))

I want to match rows in headers

and my required output is :
create new column in new dataframe.

    x   f   New
    D1  P2  1
    D2  NA  NA
    D3  NA  NA
    D4  P3  5
    D5  NA  NA

My original post mis-understood your objective. I think this code does it:

library(tidyverse)
  
## dataframe 1 has 5 observations and its 5 element    
df = data.frame(x = c("P1","P2","P3","P4","P5"), 
                f_1 = c("NA","1","NA","NA","NA"), 
                f_2= c("NA","1","NA","NA","NA"),
                f_3= c("1","7","NA","NA","NA"),
                f_4= c("NA","NA","5","NA","NA"),
                f_5= c("NA","NA","2","NA","NA"),
                stringsAsFactors = FALSE)

## Dataframe 2 has 5 observations and their allias.
df2 = data.frame(x = c("D1","D2","D3","D4","D5"),
                 f=c("f_1","f_20","f_30","f_4","f_15"))

df %>% 
  pivot_longer(-x, names_to = 'f') %>% 
  mutate(value = na_if(value, "NA")) %>% 
  drop_na() %>% 
  right_join(df2, by = 'f')
1 Like

Thanks...Its working.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.