我有这样的df:
$array = @('00155d9df9b8','00155d9df921')
foreach($mac in $array)
{
Write-Output $mac
}
现在我想创建一列以基于行值向前分配值,就像这样
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
答案 0 :(得分:2)
我们可以将'b'和paste
与't'的lead
进行分组
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>
答案 1 :(得分:2)
使用ave
within(df.temp, d <- ave(t,b,FUN = function(x) c(paste(x[-length(x)],x[-1],sep = "_"),NA)))
这样
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>