Skip to content
Prev 300152 / 398506 Next

Can't understand syntax

Hello,

It's more simple than you believe it is. One thing at a time.

First, in order to lighten the instructions, create index vectors.

test2 <- test  # save 'test' for later

na.v1 <- is.na(test[["v1"]])
na.v2 <- is.na(test[["v2"]])
na.v3 <- is.na(test[["v3"]])


Now use them.


test[[ "result" ]][ !na.v1 ] <- test[[ "v1" ]][ !na.v1 ]
test[[ "result" ]][ !na.v2 ] <- test[[ "v2" ]][ !na.v2 ]
test[[ "result" ]][ !na.v3 ] <- test[[ "v3" ]][ !na.v3 ]


Note that above, for instance, n the first line, on each side of '<-' we 
have two different types of indexing, in a certain sense.

One, a data.frame is a list of a special type, each list member is a 
(random?) variable and all variables have the same number of 
observations. So test[[ "result" ]] refers to a vector of the data.frame.

Another is the indexing of that vectors' elements. Imagine that we had 
assigned

test.res <- test[[ "result" ]]

and then accessed the elements of 'test.res' with

test.res[ !na.v1 ] <- ...etc...

That's what we are doing.
Considering that a df is a list with a tabular form, we could also use 
the row/column type of indexing. Maybe this would be more intuitive. 
Equivalent, exactly equivalent to the code above is:


test2[  !na.v1 , "result" ] <- test2[ !na.v1 , "v1" ]
test2[  !na.v2 , "result" ] <- test2[ !na.v2 , "v2" ]
test2[  !na.v3 , "result" ] <- test2[ !na.v3 , "v3" ]

all.equal(test, test2) # TRUE


Hope this helps,

Rui Barradas

Em 14-07-2012 21:22, Charles Stangor escreveu: