r - 在r中的表中组合不同行的值

标签 r format reformat reformatting

我需要在 R 中重新格式化表格。

我有一张这样的 table 。

ID  category   
1   a   
1   b   
2   c   
3   d   
4   a   
4   c  
5   a   

我想把它改成

ID  category1   category2  
1           a           b  
2           c        null  
3           d        null  
4           a           c  
5           a        null  

这在 R 中可行吗?

最佳答案

这是一个非常简单的“从长到宽”类型的 reshape 问题,但您需要一个辅助“id”(或“时间”)变量。

您可以尝试使用我的“splitstackshape”包中的 getanID 并使用 dcast 从长到宽重新整形。 getanID 将创建一个名为“.id”的新列,用作您的“时间”变量:

library(splitstackshape)
dcast.data.table(getanID(mydf, "ID"), ID ~ .id, value.var = "category")
#    ID 1  2
# 1:  1 a  b
# 2:  2 c NA
# 3:  3 d NA
# 4:  4 a  c
# 5:  5 a NA

关于r - 在r中的表中组合不同行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32486950/

相关文章:

excel - 在Excel中的文本之前添加字符而不使用公式

PHPStorm 重新格式化 - 如何禁用删除空行中的空格?

intellij-idea - 如何从 IntelliJ IDEA 中获取 "Reformat code"函数?

Java/Groovy - 简单的日期重新格式化

r - 填充有限数量的值 - tidyr Fill

R 使用时间字符串创建 XTS 对象

html - 如何在 R 中发布一个简单的 HTML 表单?

python - 在Python中调用R包的问题

Android通话记录日期转换

c++ - scanf ("%d\n"的问题,&i)