将多个列转换为R中的单个行

时间:2021-05-09 13:21:30

I have a dataframe with 1000 IDs and their values. What would be better way to convert two columns into single row based on ID. I used cast function from reshape package but it seems to convert only one column into row. Here is an example of my dataset.

我有一个包含1000个ID及其值的数据框。根据ID将两列转换为单行的更好方法是什么。我在reshape包中使用了cast函数,但似乎只将一列转换为行。这是我的数据集的一个例子。

DF <- data.frame(ID=c("x1","x1","x1","x1","x2","x2","x2","x2"),
      name1=c("T1","T1","T2","T2","T1","T1","T2","T2"),
      name2=c("C1","C2","C1","C2","C1","C2","C1","C2"),T1_val=c(1.1,1.1,2.3,2.3,1.8,1.8,7.9,7.9),C1_val=c(1.1,2.6,1.1,2.6,1.8,3.6,1.8,3.6) )

 > DF
 ID name1 name2 T1_val C1_val
 x1    T1    C1    1.1    1.1
 x1    T1    C2    1.1    2.6
 x1    T2    C1    2.3    1.1
 x1    T2    C2    2.3    2.6                
 x2    T1    C1    1.8    1.8
 x2    T1    C2    1.8    3.6
 x2    T2    C1    7.9    1.8
 x2    T2    C2    7.9    3.6

Desired output:

ID  T1   T2   C1   C2
x1  1.1  2.3  1.1  2.6
x2  1.8  7.9  1.8  3.6 

Thanks

1 个解决方案

#1


You can do it with the dplyr and tidyr combo pretty straightforward:

您可以使用dplyr和tidyr组合非常简单地完成:

library(dplyr)
library(tidyr)
DF %>%
  spread(name1, T1_val) %>%
  spread(name2, C1_val)

produces

Source: local data table [2 x 5]

  ID  T1  T2  C1  C2
1 x1 1.1 2.3 1.1 2.6
2 x2 1.8 7.9 1.8 3.6

PS: Take a look at this cheatsheet if you want to dig into these packages.

PS:如果你想深入了解这些包装,请看看这个备忘单。

#1


You can do it with the dplyr and tidyr combo pretty straightforward:

您可以使用dplyr和tidyr组合非常简单地完成:

library(dplyr)
library(tidyr)
DF %>%
  spread(name1, T1_val) %>%
  spread(name2, C1_val)

produces

Source: local data table [2 x 5]

  ID  T1  T2  C1  C2
1 x1 1.1 2.3 1.1 2.6
2 x2 1.8 7.9 1.8 3.6

PS: Take a look at this cheatsheet if you want to dig into these packages.

PS:如果你想深入了解这些包装,请看看这个备忘单。