You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将R语言中的垂直DataFrame转换为水平格式?

解决R语言DataFrame转为水平格式的问题

原始数据

首先定义目标DataFrame:

df = data.frame(x = 1:10, y=11:20)

原始输出格式:

x  y
1   1 11
2   2 12
3   3 13
4   4 14
5   5 15
6   6 16
7   7 17
8   8 18
9   9 19
10 10 20

转换方法

使用R基础包的t()函数转置数据,再调整列名即可得到目标格式:

# 转置数据并转为DataFrame
transposed_df <- as.data.frame(t(df))
# 将列名设置为原数据的行号
colnames(transposed_df) <- rownames(df)
# 输出结果
transposed_df

最终输出

运行上述代码后,得到的输出为:

1  2  3  4  5  6  7  8  9  10
x  1  2  3  4  5  6  7  8  9  10
y 11 12 13 14 15 16 17 18 19  20

内容的提问来源于stack exchange,提问作者An116

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 21:30:32