在R中将稀疏数据合并成单行的最佳方式是什么? [英] What's the best way to collapse sparse data into single rows in R?
本文介绍了在R中将稀疏数据合并成单行的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些我想在R中转换的交易数据。
I've got some transactional data that I'd like to transform in R.
df <- data.frame(
customer_id = c(123, 123, 123),
time = c(1, 2, 3),
rec_type = c('contact', 'appointment', 'sale'),
variable_1 = c('Yes', NA, NA),
variable_2 = c(NA, 'No', NA),
variable_3 = c(NA, NA, 'complete'))
数据如下所示:
customer_id time rec_type variable_1 variable_2 variable_3
123 1 contact Yes NA NA
123 2 appointment NA No NA
123 3 sale NA NA complete
本质上,我想通过删除具体时间和特定记录的数据来总结个人数据信息,然后将个人的唯一数据折叠成单行r独特的信息,所以它看起来像:
Essentially, I'm trying to summarise the data on individuals by removing the time-specific and record-specific information and then collapse the unique data on an individual into a single row for the unique information so it would look like:
customer_id variable_1 variable_2 variable_3
123 Yes No complete
在R中执行此操作的最佳方法是什么?
What's the best way to do this in R?
推荐答案
Easy with data.table
Easy with data.table
library(data.table)
setDT(mydata)[,.(na.omit(variable_1),na.omit(variable_2),na.omit(variable_3)), by=.(customer_id)]
这篇关于在R中将稀疏数据合并成单行的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文