R 基于事务数据集中现有列的新列变量“count”
我有一个包含三列的事务数据集。每行代表一个事务R 基于事务数据集中现有列的新列变量“count”,r,R,我有一个包含三列的事务数据集。每行代表一个事务 Account_from Account_to Value 1 1 2 25.0 2 1 3 30.0 3 2 1 28.0 4 2 3 10.0 5 2 4 12.0 6 3 1
Account_from Account_to Value
1 1 2 25.0
2 1 3 30.0
3 2 1 28.0
4 2 3 10.0
5 2 4 12.0
6 3 1 40.0
我想创建一个新的列变量,其中包含关于每个帐户进行和收到两列交易的数量的信息。它看起来如下所示:
Account_from Account_to Value Count_out Count_in
1 1 2 25.0 2 2
2 1 3 30.0 2 2
3 2 1 28.0 3 1
4 2 3 10.0 3 1
5 2 4 12.0 3 1
6 3 1 40.0 1 2
如何一次对整个数据集执行此操作?tidyverse提供了有用的功能-假设数据存储在数据框df中:
我们可以使用dplyr通过一些连接操作来实现这一点
这是一个在R基中的解决方案,其中使用了ave 或使用以下代码:
df <- cbind(df, with(df, list(Count_out = ave(1:nrow(df),Account_from,FUN = length),
Count_in = ave(1:nrow(df),Account_to,FUN = length)[match(Account_from,Account_to,)])))
资料
你能展示失败的地方吗?@Florisvis这是一个带有base R的解决方案,因此代码看起来可能比那些带有包dplyr或tidyverse的长
library(dplyr)
inner_join(df %>% count(Account_from, name = 'Count_out'),
df %>% count(Account_to, name = 'Count_in'),
by = c('Account_from' = 'Account_to')) %>%
right_join(df) %>%
select(names(df), Count_out, Count_in)
# Account_from Account_to Value Count_out Count_in
# <int> <int> <dbl> <int> <int>
#1 1 2 25 2 2
#2 1 3 30 2 2
#3 2 1 28 3 1
#4 2 3 10 3 1
#5 2 4 12 3 1
#6 3 1 40 1 2
df <- within(df,
list(Count_out <- ave(1:nrow(df),Account_from,FUN = length),
Count_in <- ave(1:nrow(df),Account_to,FUN = length)[match(Account_from,Account_to,)]))
> df
Account_from Account_to Value Count_in Count_out
1 1 2 25 2 2
2 1 3 30 2 2
3 2 1 28 1 3
4 2 3 10 1 3
5 2 4 12 1 3
6 3 1 40 2 1
df <- cbind(df, with(df, list(Count_out = ave(1:nrow(df),Account_from,FUN = length),
Count_in = ave(1:nrow(df),Account_to,FUN = length)[match(Account_from,Account_to,)])))
> df
Account_from Account_to Value Count_out Count_in
1 1 2 25 2 2
2 1 3 30 2 2
3 2 1 28 3 1
4 2 3 10 3 1
5 2 4 12 3 1
6 3 1 40 1 2
df <- structure(list(Account_from = c(1L, 1L, 2L, 2L, 2L, 3L), Account_to = c(2L,
3L, 1L, 3L, 4L, 1L), Value = c(25, 30, 28, 10, 12, 40), Count_out = c(2L,
2L, 3L, 3L, 3L, 1L), Count_in = c(2L, 2L, 1L, 1L, 1L, 2L)), class = "data.frame", row.names = c(NA,
-6L))