r - 创建唯一的记录数据框,其中每个申请人的多个记录都存在
问题描述
“我有一个数据框,其中存在每个申请人 id 的银行相关信息。假设申请人有多个帐户,并且数据框在多行中反映了此信息。现在我想创建一个数据框,其中每个申请人的所有信息都在一个记录”
我已经尝试过 for 和 if 循环。现在我想优化代码
com_data <- function(X) {
data_set <- data.frame(table(X$id))
a <- 3
n <- 3
for (i in 1:nrow(data_set)) {
for (j in 1:nrow(X[1:4])) {
if (data_set$Var1[i] == X$id[j]) {
count <- count + 1
#k <- j
}
if (count == 1) {
for (k in 3:ncol(X))
data_set[i, n] <- X[j, k]
n <- n + 1
} else{
for (k in 3:ncol(X))
data_set[i, n] <- X[j, k]
n <- n + 1
}
}
count = 0
n <- 3
}
return(data_set)
}
解决方案
假设您的数据框不包含列表向量,则会变得有点混乱。“Var”应该是申请人ID:
# Sample data used:
df <- data.frame(
Date = as.Date(c("27/9/2019", "28/9/2019", "1/10/2019", "2/10/2019"), "%d/%m/%y"),
dateTime = as.POSIXct(c("27/9/2019", "28/9/2019", "1/10/2019", "2/10/2019"), "%d/%m/%y %H:M:S"),
Var = as.factor(c("A", "A", "B", "B")),
Value = c(56, 50, 90, 100),
stringsAsFactors = F
)
# Convert factors & dates to strings:
convert_descriptors_to_char <- function(df){
as.data.frame(lapply(df,
function(x){
if(is.factor(x) | inherits(x, "Date") | inherits(x, "POSIXct") | inherits(x, "POSIXlt")) {
as.character(trimws(x, which = "both"))
} else{
x
}
}
),
stringsAsFactors = FALSE)
}
# Convert data types:
df <- convert_descriptors_to_char(df)
# Merge the separate lists into one:
df_aggd <- lapply(df, function(x){
if(is.character(x)){
aggregate(x~df$Var, df, paste0, collapse = ", ")
}else if(is.numeric(x)){
aggregate(x~df$Var, df, sum)
}else{
x
}
}
)
# Vector to rename "x" to:
x_vect_names <- names(sapply(df_aggd, function(x){deparse(substitute(x))}))
# Iterate through list to rename:
for (i in seq_along(df_aggd)){
colnames(df_aggd[[i]]) <- c("Var", x_vect_names[i])
}
# Remove Var df:
df_aggd <- df_aggd[names(df_aggd) != "Var"]
# Merge the separate dataframes into one:
Reduce(function(x, y){merge(x, y, all = TRUE, by = intersect(colnames(x), colnames(y)))}, df_aggd)
推荐阅读
- javascript - 如何将 JS 数组传输到另一个 JS 文件
- javascript - 反应 Axios 句柄 401
- html - 元素只占屏幕的一半
- ruby-on-rails - Heroku上的AWS存储丢失图像rails 5 ActionController::RoutingError(没有路由匹配[GET]
- stm32 - qemu-stm32 中的模拟按钮
- vba - 从 Word 模板启动文件夹中删除文件
- php - PHP7.2.24 问题:调用未定义函数 mysqli_connect()
- python - Python:循环访问假期的国家列表
- javascript - 将数组推入js中的另一个数组中?
- javascript - 当站点加载时在后台调用另一个,但用户仍然在同一页面上