R中的水平到垂直格式 [英] Horizontal to Vertical Format in R

查看:107
本文介绍了R中的水平到垂直格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含这些值的数据框:

I have a data frame with these values:

X1  X2      X3
s1  45.11   1
s1  45.13   1
s1  53.42   2
s1  51.41   2
s2  96.76   3
s2  96.65   3
s4  77.9    4
s1  80.46   5
s3  43.58   2
s1  43.12   2
s1  41.51   3
s4  41.97   3
s1  108.97  6
s3  117.46  6
s4  40      3
s4  40      3
s5  25.4    1
s5  25.5    1

我想将其转换为这种格式的数据框:

I want to convert it to a data frame in this kind of format:

    s1     s2   s3  s4  s5
1   45.12   0   0   0   25.45
2   49.32   0   43.58   0   0

在这里,值是 X2 列上面的那些符合条件,即,是行 s1 的一部分,值为 X3 为1.

In this, the values are the mean values of the X2 column above that match the criteria, i.e., are part of row s1 and have the value of X3 as 1.

如何在R中实现?

推荐答案

你可以在基础R中这样做(假设您的数据位于数据框架 df ):

You could do this in base R (suppose your data are in data frame df):

r <- aggregate(X2~X1+X3, df[df$X3 %in% c(1,2),], mean)
round(t(xtabs(X2~X1+X3, r)), 2)

#   X1
#X3     s1    s2    s3    s4    s5
#  1 45.12  0.00  0.00  0.00 25.45
#  2 49.32  0.00 43.58  0.00  0.00

这篇关于R中的水平到垂直格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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