【发布时间】:2019-01-07 15:36:17
【问题描述】:
unique_ref priority_201801 balance_201801 action_201801 priority_201802 balance_201802 action_201802 priority_201803 balance_201803 action_201803
1 1 3 30 text,letter 1 60 letter 2 30 text
2 2 2 -20 visit 1 -40 text 2 -40 call
3 3 3 35 letter 1 35 call 3 -50 text
4 4 0 -100 call 2 0 visit 2 100 call
priority_201804 balance_201804 action_201804
1 99 0 text
2 0 -20 visit
3 0 -50 letter
4 0 -100 text
以上是我的数据集示例。我想搜索每个动作,寻找动作“文本”的第一个实例,这将是第 0 周,然后我想排列接下来几周的优先级和余额,如第 1 周、第 2 周等。
理想的输出:
unique_ref week0_priority week0_balance week0_action week1_priority week1_balance week1_action week2_priority week2_balance week2_action
1 1 3 30 text 1 60 letter 2 30 text
2 2 1 -40 text 2 -40 call 0 -20 visit
3 3 3 -50 text 0 -40 letter No Data No Data No Data
4 4 0 -100 text No Data No Data No Data No Data No Data No Data
week3_priority week3_balance week3_action
1 99 0 text
2 No Data No Data No Data
3 No Data No Data No Data
4 No Data No Data No Data
可重现的数据示例:
unique_ref=c(1,2,3,4)
priority_201801=c('3','2','3','0')
balance_201801=c('30','-20','35','-100')
action_201801=c('text,letter','visit','letter','call')
priority_201802=c('1','1','1','2')
balance_201802=c('60','-40','35','0')
action_201802=c('letter','text', 'call', 'visit')
priority_201803=c('2','2','3','2')
balance_201803=c('30','-40','-50','100')
action_201803=c('text','call','text','call')
priority_201804=c('99','0','0','0')
balance_201804=c('0','-20','-50','-100')
action_201804=c('text','visit','letter','text')
df3=as.data.frame(cbind(unique_ref,priority_201801,balance_201801,action_201801,priority_201802,balance_201802,action_201802,priority_201803,
balance_201803,action_201803,priority_201804,balance_201804,action_201804))
【问题讨论】:
-
我不太确定你到底想要达到什么目的,但也许尝试将所有信息放在 data.frame 中,因为显然某些信息只是列名的一部分,这是不是正确的数据结构。我认为添加日期列是最简单的。
-
@hannes101 我有这种格式的数据,我希望它是理想的输出。这就是我问这个问题的原因,这个问题有没有完全不清楚的部分?很高兴澄清任何困惑。
-
我只是说将其转换为长格式并在修改后恢复为宽格式可能会更容易。
标签: r loops for-loop if-statement