Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match row value with column name and extract value in R

Tags:

r

match

I have a table where I need to choose all the values in the Data column, match with the column names and take the value from that row. Ex. Data column: choose A1, find column name with same name (A1 )and take the value (1), choose A3, find column name with same name (A3) and take the value (11) and then print it to a table.

Can somebody help me, I am new using R and I do not know where to start.

A1  A2  A3   Data
1   5   9   A1  
2   6   10  A2
3   7   11  A3
4   8   12  A4
like image 335
anna Avatar asked Feb 03 '15 11:02

anna


People also ask

How do I find rows with certain values in R?

You can use the following basic syntax to find the rows of a data frame in R in which a certain value appears in any of the columns: library(dplyr) df %>% filter_all(any_vars(. %in% c('value1', 'value2', ...)))


1 Answers

If you create your data.frame with the row.names as your Data column, then it can be as simple as:

mydf <- read.table(text = "A1 A2 A3 Data 
1 5 9 A1
2 6 10 A2 
3 7 11 A3 
4 8 12 A4", header = TRUE, row.names = "Data")

sapply(row.names(mydf), function(x) mydf[[x, x]])
## $A1
## [1] 1
## 
## $A2
## [1] 6
## 
## $A3
## [1] 11
## 
## $A4
## NULL
## 

mydf[x,x] simply returns the element of my df, in the row with the name x and the column with name x. You may need to tweak this output to match your goal.

like image 76
zelite Avatar answered Nov 14 '22 23:11

zelite