# extract first value from multiple columns

#### leonedelman

##### New Member
i am trying to do this in R. it is equivalent to the stata command
Code:
rowfirst
suppose i have four columns as shown below (T1, T2, T3, T4). I want to create a new column (TX) which contains for each row the first element in columns T1:T4.

Code:
ID T1 T2 T3 T4

A  0  2  4  5
B  .  .  6  5
C  .  8  6  1
D  .  .  .  9

ID TX
A   0
B   6
C   8
D   9
thank you everyone!!

#### Dason

Would those dots be stored as NA?

#### leonedelman

##### New Member
Would those dots be stored as NA?
Yes:yup: the dots below are stored as NA. thank you for your reply!

#### pardha

##### New Member
You can do some thing like this:

Assuming your data frame is called data

data$TX=as.vector(data[1,]) if in case no. of columns is not equal to no. of rows you can use below command it will replace empty values in TX with NA iris$v1=as.vector(c(iris[1,],rep(NA,nrow(iris)-ncol(iris))))

#### rogojel

##### TS Contributor
hi,
you would need to define a function to return the index of the first non NA in a vector, then use apply (or aggregate) on the data feame.

My shot at the function would be

NonNA= function(v){
return (match(0, 1:length(v)*is.na(v))
}

to return the first value instead of the index:

FirstNA= function(v){
ind= (match(0, 1:length(v)*is.na(v))
return(v[ind])
}

regards