R:将行数据透视为列,并使用N / A作为缺失值 [英] R: Pivot the rows into columns and use N/A's for missing values

查看:243
本文介绍了R:将行数据透视为列,并使用N / A作为缺失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框看起来像这样

I have a dataframe that looks something like this

NUM <- c("45", "45", "45", "45", "48", "50", "66", "66", "66", "68")
Type <- c("A", "F", "C", "B", "D", "A", "E", "C", "F", "D")
Points <- c(9.2,60.8,22.9,1012.7,18.7,11.1,67.2,63.1,16.7,58.4)

df1 <- data.frame(NUM,Type,Points)

df1:

+-----+------+--------+
| NUM | TYPE | Points |
+-----+------+--------+
|  45 | A    | 9.2    |
|  45 | F    | 60.8   |
|  45 | C    | 22.9   |
|  45 | B    | 1012.7 |
|  48 | D    | 18.7   |
|  50 | A    | 11.1   |
|  66 | E    | 67.2   |
|  66 | C    | 63.1   |
|  66 | F    | 16.7   |
|  65 | D    | 58.4   |
+-----+------+--------+

我正在尝试获取一个输出,它将类型列中的行转换为单独的列。

I am trying to obtain an output that takes the rows in type column to convert it to individual columns.

所需的输出:

+-----+----------+----------+----------+----------+----------+----------+
| NUM | Points.A | Points.B | Points.C | Points.D | Points.E | Points.F |
+-----+----------+----------+----------+----------+----------+----------+
|  45 | 9.2      | 1012.7   | 22.9     | N/A      | N/A      | 60.8     |
|  48 | N/A      | N/A      | N/A      | 18.7     | N/A      | N/A      |
|  50 | 11.1     | N/A      | N/A      | N/A      | N/A      | N/A      |
|  66 | N/A      | N/A      | 63.1     | N/A      | 67.2     | 16.7     |
|  65 | N/A      | N/A      | N/A      | N/A      | 58.4     | N/A      |
+-----+----------+----------+----------+----------+----------+----------+

我尝试使用melt(df1)但是错误地执行,因为行中的值是NUM值而不是点。请告诉我如何解决这个问题。

I tried using melt(df1) but doing it wrongly since the values in the rows are the NUM values rather than points. Kindly let me know how I could go about solving this.

推荐答案

您正在寻找一个基本的长到广泛重塑过程。

You are looking for a basic "long" to "wide" reshaping process.

在基地R中,您可以使用臭名昭着的 reshape 。对于这种类型的数据,语法非常简单:

In base R, you can use the notorious reshape. For this type of data, the syntax is quite straightforward:

reshape(df1, direction = "wide", idvar = "NUM", timevar = "Type")
#    NUM Points.A Points.F Points.C Points.B Points.D Points.E
# 1   45      9.2     60.8     22.9   1012.7       NA       NA
# 5   48       NA       NA       NA       NA     18.7       NA
# 6   50     11.1       NA       NA       NA       NA       NA
# 7   66       NA     16.7     63.1       NA       NA     67.2
# 10  68       NA       NA       NA       NA     58.4       NA

你也可以使用tidyr包,几个函数只是包装 reshape2 但使用不同的语法。在这种情况下,语法将是:

You can also use the "tidyr" package, for several functions just wrap reshape2 but uses different syntax. In this case, the syntax would be:

> library(tidyr)
> spread(df1, Type, Points)

这篇关于R:将行数据透视为列,并使用N / A作为缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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