[英]R: How to rename columns with row value dataframe
I am trying to rename the columns of my data frame with the row values.我正在尝试使用行值重命名数据框的列。 I have the following:我有以下内容:
FIRM TIME V_Ri
1 A EAGLE 14DEC1994 740 -0.0005039933
2 A EAGLE 14DEC1994 741 0.0000000000
3 A EAGLE 14DEC1994 742 0.0238607800
4 A EAGLE 14DEC1994 743 -0.0125612300
5 A EAGLE 14DEC1994 744 -0.0134325100
And I would like to obtain:我想获得:
FIRM 740 741 etc.
1 A EAGLE 14DEC1994 -0.0005039933 0.0000000000
I have tried by transposing, but couldn't reach the desired result.我尝试过转置,但无法达到预期的结果。 Any hints?有什么提示吗?
This is a problem for pivot_wider()
from the tidyr
package.这是来自tidyr
package 的pivot_wider()
的问题。
If your data is in a data.frame called df
, do the following:如果您的数据位于名为df
的 data.frame 中,请执行以下操作:
library(tidyr)
df %>%
pivot_wider(names_from = "TIME", values_from = "V_Ri")
# A tibble: 1 x 6
FIRM `740` `741` `742` `743` `744`
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A EAGLE 14DEC1994 -0.000504 0 0.0239 -0.0126 -0.0134
Note that the column names have back ticks around the numbers.请注意,列名在数字周围有反引号。 Names of objects, including column names, are not typically allowed to start with numerals.对象的名称,包括列名,通常不允许以数字开头。 The back tick encapsulates nonstandard names.反引号封装了非标准名称。
Sample data used:使用的样本数据:
df <- structure(list(FIRM = c("A EAGLE 14DEC1994", "A EAGLE 14DEC1994",
"A EAGLE 14DEC1994", "A EAGLE 14DEC1994",
"A EAGLE 14DEC1994"),
TIME = c(740, 741, 742, 743, 744),
V_Ri = c(-0.0005039933, 0, 0.02386078, -0.01256123,
-0.01343251)),
row.names = c(NA, -5L),
class = c("tbl_df", "tbl", "data.frame"))
Base R one-liner (Thanks @Ben Norris for the dataset):基本 R 单线(感谢@Ben Norris 提供数据集):
spread_df <- as.data.frame.matrix(xtabs(V_Ri ~ FIRM+TIME, df))
If you want to reset the index column and push the row.names back to a FIRM vector:如果要重置索引列并将 row.names 推回 FIRM 向量:
data.frame(FIRM = row.names(spread_df), spread_df, row.names = NULL)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.