如何在R中拆分列? [英] How to split a column in R?

查看:33
本文介绍了如何在R中拆分列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何将一列拆分为多列吗?例如:我想拆分score"和class"列,然后将grade"列的值作为列名.在我的数据中,我在等级"列中有 50 个不同的值,而不是在下面的示例中只有两个.在数据框 2 中,行名称是数据框 1 中列class"的值.

Anyone know how can I split a column to multiple ones? For example: I want to split column "score" and "class", then make the values of column "grade" as column name. In my data, I have 50 different values in column "grade" instead of only two in the example below. In the data frame 2, the row names are the values of column "class" in data frame 1.

数据框 1

class   grade   score
A          a    12
B          a    45
C          a    75
D          a    18
E          a    6
A          b    45
B          b    92
C          b    78
D          b    36
E          b    39

数据框 2

    a   b
A   12  45
B   45  92
C   75  78
D   18  36
E   6   39

推荐答案

Base R 的 unstack 开箱即用:

Base R's unstack does this out of the box:

unstack(df, score ~ grade)
#   a  b
#1 12 45
#2 45 92
#3 75 78
#4 18 36
#5  6 39

xtabs 一样:

as.data.frame.matrix(xtabs(score ~ class + grade, data=df))

#   a  b
#A 12 45
#B 45 92
#C 75 78
#D 18 36
#E  6 39

这篇关于如何在R中拆分列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆