将 DF 转置一定数量的行
Transposing a DF by a certain number of lines
假设我有一个如下所示的数据框:
mydf <- data.frame(col0=c("row1","row2","row3"),
col1=c(AAA1),
col2=c(BBB1),
col3=c(CCC1),
col4=c(AAA2),
col5=c(BBB2),
col6=c(CCC2))
mydf
# col0 col1
# row1 AAA1
# row2 BBB1
# row3 CCC1
# row4 AAA2
# row5 BBB2
# row6 CCC2
我希望它每 3 行转置一次,这样它看起来像这样:
# col0 col1 col2 col3
# row1 AAA1 BBB1 CCC1
# row2 AAA2 BBB2 CCC2
我该怎么做?有没有做这种转置的功能?像 pivot_wider ou spread 这样的东西可以设置为重复每 X 行?
您需要添加一个数据透视列和一个结束 ID 列以使其不会折叠:
df <- data.frame(
col0 = c("a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3")
)
print(df)
col0
1 a1
2 b1
3 c1
4 a2
5 b2
6 c2
7 a3
8 b3
9 c3
现在,转换:
df <- df %>%
mutate(
col_pivot = rep(1:3, length.out = nrow(.)),
end_id = rep(1:(nrow(.)/3), each = 3) # this prevents the dataframe from collapsing to 1 row
) %>%
pivot_wider(
names_from = col_pivot,
names_prefix = "col_",
values_from = col0
)
print(df)
# A tibble: 3 × 4
end_id col_1 col_2 col_3
<int> <chr> <chr> <chr>
1 1 a1 b1 c1
2 2 a2 b2 c2
3 3 a3 b3 c3
假设我有一个如下所示的数据框:
mydf <- data.frame(col0=c("row1","row2","row3"),
col1=c(AAA1),
col2=c(BBB1),
col3=c(CCC1),
col4=c(AAA2),
col5=c(BBB2),
col6=c(CCC2))
mydf
# col0 col1
# row1 AAA1
# row2 BBB1
# row3 CCC1
# row4 AAA2
# row5 BBB2
# row6 CCC2
我希望它每 3 行转置一次,这样它看起来像这样:
# col0 col1 col2 col3
# row1 AAA1 BBB1 CCC1
# row2 AAA2 BBB2 CCC2
我该怎么做?有没有做这种转置的功能?像 pivot_wider ou spread 这样的东西可以设置为重复每 X 行?
您需要添加一个数据透视列和一个结束 ID 列以使其不会折叠:
df <- data.frame(
col0 = c("a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3")
)
print(df)
col0
1 a1
2 b1
3 c1
4 a2
5 b2
6 c2
7 a3
8 b3
9 c3
现在,转换:
df <- df %>%
mutate(
col_pivot = rep(1:3, length.out = nrow(.)),
end_id = rep(1:(nrow(.)/3), each = 3) # this prevents the dataframe from collapsing to 1 row
) %>%
pivot_wider(
names_from = col_pivot,
names_prefix = "col_",
values_from = col0
)
print(df)
# A tibble: 3 × 4
end_id col_1 col_2 col_3
<int> <chr> <chr> <chr>
1 1 a1 b1 c1
2 2 a2 b2 c2
3 3 a3 b3 c3