Keep names with apply

153 views Asked by At

I have a named vector like:

mochila

r01 r02 r03 r04 
0   0   0   0   

And a dataframe

data
        req_ID effort satisfaction
    1     r01      1           62
    2     r02      4           55
    3     r03      2           29
    4     r04      3           41

If I change a value manually, it keep the name

mochila[1] <- 1
mochila

r01 r02 r03 r04 
  1   0   0   0  

But, for example, if I apply like this

myfun<- function(x){
  return(1)
}

mochila <- apply(data,1,myfun)

Result:

mochila

 [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

I lost all named position, Is there some way to keep names?

1

There are 1 answers

0
Frank On BEST ANSWER

mochila[] <- expr should work.

From ?Extract:

An empty index selects all values: this is most often used to replace all the entries but keep the attributes.