gpt4 book ai didi

r - 使用另一列中的先前信息更改列中的数据

转载 作者:行者123 更新时间:2023-12-03 16:49:17 24 4
gpt4 key购买 nike

我有一个包含三列的数据集。栏目user有两个 Action ,包括action1action2 . action2仅包含信息如果 action1栏目有A数据。我要串联 P数据在 action1与之前的数据在 action2 .例如,如果 action2ac ,下一行有 Paction1 ,我要换P进入 Pac ,并将继续(所有 P 变成 Pac )直到 action2改变。请注意,此过程应为每个 user 重复。 .

df<-read.table(text="
user action1 action2
1 A a
1 B NA
1 P NA
1 P NA
1 A ac
1 P NA
2 B NA
2 P NA
2 A aa
2 P NA
2 AB aa",header=T)

result: (I highlighted those rows that infected)
user action1 action2
1 A a
1 B NA
1 Pa NA <-
1 Pa NA <-
1 A ac
1 Pac NA <-
2 B NA
2 P NA
2 A aa
2 Paa NA <-
2 AB NA

谢谢

最佳答案

library('data.table')
library('zoo')
# Using zoo::na.locf(), fill NA with the previous value and group by user. Also `na.locf` will not remove NA.
setDT(df)[, V3 := na.locf(action2, na.rm = FALSE), by = .(user)]
# combine action1 with V3 column if action1 is equal to 'P' and it is not NA.
df[action1 == 'P' & !(is.na(V3)), action1 := paste0(action1, V3)]
df[, V3 := NULL] # remove V3 column
df
# user action1 action2
# 1: 1 A a
# 2: 1 B NA
# 3: 1 Pa NA
# 4: 1 Pa NA
# 5: 1 A ac
# 6: 1 Pac NA
# 7: 2 B NA
# 8: 2 P NA
# 9: 2 A aa
# 10: 2 Paa NA
# 11: 2 AB aa

数据:
df<-read.table(text="
user action1 action2
1 A a
1 B NA
1 P NA
1 P NA
1 A ac
1 P NA
2 B NA
2 P NA
2 A aa
2 P NA
2 AB aa",header=T, stringsAsFactors = FALSE)

关于r - 使用另一列中的先前信息更改列中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61086776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com