简体   繁体   中英

vectorise rows of a dataframe, apply vector function, return to original dataframe r

Given the following df:

a=c('a','b','c')
b=c(1,2,5)
c=c(2,3,4)
d=c(2,1,6)
df=data.frame(a,b,c,d)

  a b c d
1 a 1 2 2
2 b 2 3 1
3 c 5 4 6

I'd like to apply a function that normally takes a vector (and returns a vector) like cummax row by row to the columns in position b to d .

Then, I'd like to have the output back in the df, either as a vector in a new column of the df, or replacing the original data.

I'd like to avoid writing it as a for loop that would iterate every row, pull out the content of the cells into a vector, do its thing and put it back.

Is there a more efficient way? I've given the apply family functions a go, but I'm struggling to first get a good way to vectorise content of columns by row and get the right output.

the final output could look something like that (imagining I've applied a cummax() function).

    a b c d 
1   a 1 2 2
2   b 2 3 3
3   c 5 5 6

or

    a b c d output
1   a 1 2 2 (1,2,2)
2   b 2 3 1 (2,3,3)
3   c 5 4 6 (5,5,6)

where output is a vector.

Seems this would just be a simple apply problem that you want to cbind to df:

> cbind(df, apply(df[ , 4:2]   # work with columns in reverse order
                     , 1,      # do it row-by-row
                      cummax) )
  a b c d 1 2 3
d a 1 2 2 2 1 6
c b 2 3 1 2 3 6
b c 5 4 6 2 3 6

Ouch. Bitten by failing to notice that this would be returned in a column oriented matrix and need to transpose that result; Such a newbie mistake. But it does show the value of having a question with a reproducible dataset I suppose.

> cbind(df, t(apply(df[ , 4:2] , 1, cummax) ) )
  a b c d d c b
1 a 1 2 2 2 2 2
2 b 2 3 1 1 3 3
3 c 5 4 6 6 6 6

To destructively assign the result to df you would just use:

df <-   # .... that code.

This does the concatenation with commas (and as a result no longer needs to be transposed:

> cbind(df, output=apply(df[ , 4:2] , 1, function(x) paste( cummax(x), collapse=",") ) )
  a b c d output
1 a 1 2 2  2,2,2
2 b 2 3 1  1,3,3
3 c 5 4 6  6,6,6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM