如何将四列转换为两列

时间:2019-06-21 02:16:37

标签: r dataframe

我必须进行Fisher检验来比较纳斯达克和奈斯的一些股票之间的差异。 我有一列包含纳斯达克股票交易所的收益,而另一列与奈斯股票交易所的收益是这样的:

NasdaqStocks NyseStocks Nasdaq   Nyse
1            5          nasdaq   nyse
2            6          nasdaq   nyse
3            7          nasdaq   nyse
4            8          nasdaq   nyse

我需要这样的东西

Returns Market
1        nasdaq
2        nasdaq
3        nasdaq
4        nasdaq
5        nyse
6        nyse
7        nyse
8        nyse
9        nyse

2 个答案:

答案 0 :(得分:1)

如果只有4列,我们可以unlist它们并创建一个新的数据框

data.frame(Returns = unlist(df[1:2]), Market = unlist(df[3:4]), row.names = NULL)

#  Returns Market
#1       1 nasdaq
#2       2 nasdaq
#3       3 nasdaq
#4       4 nasdaq
#5       5   nyse
#6       6   nyse
#7       7   nyse
#8       8   nyse

答案 1 :(得分:0)

您可以使用reshape

reshape(d[1:2], varying=names(d)[1:2], v.names="Returns", direction="long", 
        times=tolower(gsub("Stocks", "", names(d)[1:2])), timevar="Market")
#          Market Returns id
# 1.nasdaq nasdaq       1  1
# 2.nasdaq nasdaq       2  2
# 3.nasdaq nasdaq       3  3
# 4.nasdaq nasdaq       4  4
# 1.nyse     nyse       5  1
# 2.nyse     nyse       6  2
# 3.nyse     nyse       7  3
# 4.nyse     nyse       8  4

数据

d <- structure(list(NasdaqStocks = 1:4, NyseStocks = 5:8, Nasdaq = structure(c(1L, 
1L, 1L, 1L), .Label = "nasdaq", class = "factor"), Nyse = structure(c(1L, 
1L, 1L, 1L), .Label = "nyse", class = "factor")), row.names = c(NA, 
-4L), class = "data.frame")