[英]R function for collapsing multiple ranges of different columns from wide to long format?
我有一個數據集,每行中有多個不同范圍的列(每行對應一個人),如下所示。 不同列類型的每個實例都有 3 個級別(0,1 和 2)。
id col1_0 col1_1 col1_2 col2_0 col2_1 col2_2 col3_0 col3_1 col3_2
1 0 1 3 2 2 3 3 4 5
2 1 1 2 2 4 7 4 5 5
.
.
etc.
對於每個 id,我需要將所有 col1 折疊到一列中,將所有 col2 折疊到另一列中,並將所有 col3 折疊到另一列中。 如下。
id x col1 col2 col4
1 0 0 2 3
1 1 1 2 4
1 2 3 3 5
2 0 1 2 4
2 1 1 4 5
2 2 1 7 5
.
.
etc.
此外,我還需要為每個 id 創建一個值為 0,1 和 2 的 x 列。 但是,我只設法使用下面的代碼折疊第一個列范圍(col1)。
library(tidyverse)
longer_data <- dataframe %>%
group_by(id) %>%
pivot_longer(col1_0:col1_2, names_to = "x1", values_to = "col1")
x1 在這里創建一個具有原始列名的列。 所以我會創建一個額外的 x 列,它只保留原始列名的最后一個數字。
有沒有辦法做到這一點? 提前謝謝了!
我們不需要任何group_by
。 它可以通過在pivot_longer
中指定names_sep
和.value
直接使用names_to
完成。 注意.value
和x
的順序。 這意味着該列的值應該 go 在_
之前的每個前綴中,並且帶有后綴存根的新列進入“x”
library(dplyr)
library(tidyr)
df1 %>%
pivot_longer(cols = -id, names_to = c('.value', 'x'), names_sep = "_")
-輸出
# A tibble: 6 x 5
# id x col1 col2 col3
# <int> <chr> <int> <int> <int>
#1 1 0 0 2 3
#2 1 1 1 2 4
#3 1 2 3 3 5
#4 2 0 1 2 4
#5 2 1 1 4 5
#6 2 2 2 7 5
df1 <- structure(list(id = 1:2, col1_0 = 0:1, col1_1 = c(1L, 1L), col1_2 = 3:2,
col2_0 = c(2L, 2L), col2_1 = c(2L, 4L), col2_2 = c(3L, 7L
), col3_0 = 3:4, col3_1 = 4:5, col3_2 = c(5L, 5L)),
class = "data.frame", row.names = c(NA,
-2L))
這是一個使用reshape
的基本 R 選項,其中timevar="x"
創建一個名為x
的列,而sep="_"
有助於獲取原始列名的最后一個數字。
res <- reshape(
df,
direction = "long",
idvar = "id",
varying = -1,
timevar = "x",
sep = "_"
)
res <- res[order(res$id), ]
> res
id x col1 col2 col3
1.0 1 0 0 2 3
1.1 1 1 1 2 4
1.2 1 2 3 3 5
2.0 2 0 1 2 4
2.1 2 1 1 4 5
2.2 2 2 2 7 5
數據
> dput(df)
structure(list(id = 1:2, col1_0 = 0:1, col1_1 = c(1L, 1L), col1_2 = 3:2,
col2_0 = c(2L, 2L), col2_1 = c(2L, 4L), col2_2 = c(3L, 7L
), col3_0 = 3:4, col3_1 = 4:5, col3_2 = c(5L, 5L)), class = "data.frame", row.names = c(NA,
-2L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.