R: Assign Variable Names based on a matrix's columns -
i (very) new user r, , trying replicate matlab codes here (prefer r octave @ stage).
i have following matrix df
:
variable value th 100 tw 100 gap 30
i'd able assign variables, based on first column, values in second. basically, th = 100
, tw = 100
, gap = 30
.
my end aim able manipulate data in following manner:
difference <- th-gap
edit:
>dput(df) structure(list(s = structure(1:3, .label = c("aa", "bb", "cc" ), class = "factor"), n = c(2, 3, 5)), .names = c("s", "n"), row.names = c(na, -3l), class = "data.frame")
you have adata.frame
different object entirely matrix
. matrix
atomic vector dimension attributes wrap matrix
. atomic vector matrix can contain data of single type, cannot have character
data mixed numeric
data. data.frame
on other hand type of list, each list element atomic vector of same length (the length gives number of rows, number of elements in list number of columns). each list
element can hold data of different type.
so lets assume have data.frame
...
# construct data df <- read.table( text = "variable value th 100 tw 100 gap 30" , h = true ) df # variable value #1 th 100 #2 tw 100 #3 gap 30 # subset data.frame values want using `[` operator difference <- df[ df$variable == 'th' , 'value' ] - df[ df$variable == 'gap' , 'value' ] #[1] 70
we can subset data.frame
using [
operator. first argument inside [,]
refers rows , second argument columns. [ df$variable == 'th' , 'value' ]
returns logical vector in rows argument true
when variable == 'th'
, returns rows meet condition column called value
.
Comments
Post a Comment