简体   繁体   中英

Row cell value based on other columns value

I have a df like this:

df.temp = data.frame("t" = c(1,2,3,5,1,3,2,5), "a" = c("a1","a2","a1","a1","a1","a1","a1","a1"), "b" = 
c("b1","b1","b1","b1","b2","b2","b2","b2"))

> df.temp
  t  a  b
1 1 a1 b1
2 2 a2 b1
3 3 a1 b1
4 5 a1 b1
5 1 a1 b2
6 3 a1 b2
7 2 a1 b2
8 5 a1 b2

Now I want to create a column to assign value based on row value going forward, like this

  t  a  b  d
1 1 a1 b1 1_2
2 2 a2 b1 2_3
3 3 a1 b1 3_5
4 5 a1 b1 NA
5 1 a1 b2 1_3
6 3 a1 b2 3_2
7 2 a1 b2 2_5
8 5 a1 b2 NA

We can group by 'b' and paste the 't' with the lead of 't'

library(dplyr)
library(stringr)
df.temp %>% 
      group_by(b) %>% 
      mutate(d = str_c(t, lead(t), sep="_"))
# A tibble: 8 x 4
# Groups:   b [2]
#      t a     b     d    
#  <dbl> <chr> <chr> <chr>
#1     1 a1    b1    1_2  
#2     2 a2    b1    2_3  
#3     3 a1    b1    3_5  
#4     5 a1    b1    <NA> 
#5     1 a1    b2    1_3  
#6     3 a1    b2    3_2  
#7     2 a1    b2    2_5  
#8     5 a1    b2    <NA> 

A base R option using ave

within(df.temp, d <- ave(t,b,FUN = function(x) c(paste(x[-length(x)],x[-1],sep = "_"),NA)))

such that

  t  a  b    d
1 1 a1 b1  1_2
2 2 a2 b1  2_3
3 3 a1 b1  3_5
4 5 a1 b1 <NA>
5 1 a1 b2  1_3
6 3 a1 b2  3_2
7 2 a1 b2  2_5
8 5 a1 b2 <NA>

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