I would like to add values I have stored in a dataframe, to the place in the matrix where they belong.
This is the data:
dataframe:
df <- read.table(text=' A B C
name1 add1 1
name2 add1 2
name3 add1 3
name1 add2 1
name2 add2 2 ', header=TRUE)
> df
A B C
1 name1 add1 1
2 name2 add1 2
3 name3 add1 3
4 name1 add2 1
5 name2 add2 2
Matrix:
ma <- matrix(NA, ncol=2, nrow=3)
colnames(ma)<-c('add1', 'add2')
rownames(ma)<-c('name1', 'name2', 'name3')
> ma
add1 add2
name1 NA NA
name2 NA NA
name3 NA NA
So the unique entries in df$A
are the rows of ma
The unique entries in df$B
are the column of ma
The resulting matrix would look like this:
> ma
add1 add2
name1 1 1
name2 2 2
name3 3 NA
Note that the dataframe could be in any order, and some combinations of name and add may not exist (so there should still be an NA
in ma
)
So far, I was not able to produce working code to take the values out of df
and write them into ma
I would be grateful for your suggestions.
Thank you!