我想重新安排我的数据框从长到宽,插入的地方没有给定变量的信息。
R中的数据框如下所示:
fish_df1 <- read.table(header=T, sep=",", text="
species,st,var01,var02,var03,var04
cod,1,45,52.3,1001.0,A
cod,1,23,45.6,2003.0,D
cod,1,51,33.2,5003.0,B
cod,1,62,12.3,23.0,E
cod,10,35,65.7,123.0,C
cod,10,86,39.87,90.0,A
cod,10,46,39.22,908.0,A
cod,10,37,38.57,99.0,A
cod,14,86,37.92,12242.7,B
cod,14,36,37.27,16697.7,A
cod,14,66,36.62,1203.7,C
cod,14,72,35.97,1465.9,B
herring,1,75,35.32,1728.1,A
herring,1,78,34.67,1990.3,A
herring,1,99,34.02,2252.5,B
herring,1,49,33.37,908.0,B
herring,10,51,32.72,99.0,C
herring,10,32,32.07,93.4,C
herring,10,35,31.42,808.0,A
herring,10,21,30.77,1230.0,A
herring,12,32,30.12,4560.0,A
herring,12,45,29.47,5951.3,A
herring,12,36,28.82,7827.3,A
herring,12,35,28.17,9703.3,C
eel,1,88,35.32,1728.1,A
eel,1,66,34.67,1990.3,A
eel,1,74,34.02,2252.5,B
eel,1,37,33.37,908.0,B
eel,10,78,30.12,4560.0,A
eel,10,89,29.47,5951.3,A
eel,10,27,28.82,7827.3,A
eel,10,34,28.17,9703.3,C
")
我想重新安排数据框,使其看起来像这样:
fish_df2 <- read.table(header=T, sep=",", text="
species.cod,st.cod,var01.cod,var02.cod,var03.cod,var04.cod,species.herring,st.herring,var01.herring,var02.herring,var03.herring,var04.herring,species.eel,st.eel,var01.eel,var02.eel,var03.eel,var04.eel
cod,1,45,52.3,1001.0,A,herring,1,75,35.32,1728.1,A,eel,1,88,35.32,1728.1,A
cod,1,23,45.6,2003.0,D,herring,1,78,34.67,1990.3,A,eel,1,66,34.67,1990.3,A
cod,1,51,33.2,5003.0,B,herring,1,99,34.02,2252.5,B,eel,1,74,34.02,2252.5,B
cod,1,62,12.3,23.0,E,herring,1,49,33.37,908.0,B,eel,1,37,33.37,908.0,B
cod,10,35,65.7,123.0,C,herring,10,51,32.72,99.0,C,eel,10,78,30.12,4560.0,A
cod,10,86,39.87,90.0,A,herring,10,32,32.07,93.4,C,eel,10,89,29.47,5951.3,A
cod,10,46,39.22,908.0,A,herring,10,35,31.42,808.0,A,eel,10,27,28.82,7827.3,A
cod,10,37,38.57,99.0,A,herring,10,21,30.77,1230.0,A,eel,10,34,28.17,9703.3,C
cod,12,NA,NA,NA,NA,herring,12,32,30.12,4560.0,A,eel,12,NA,NA,NA,NA
cod,12,NA,NA,NA,NA,herring,12,45,29.47,5951.3,A,eel,12,NA,NA,NA,NA
cod,12,NA,NA,NA,NA,herring,12,36,28.82,7827.3,A,eel,12,NA,NA,NA,NA
cod,12,NA,NA,NA,NA,herring,12,35,28.17,9703.3,C,eel,12,NA,NA,NA,NA
cod,14,86,37.92,12242.7,B,herring,14,NA,NA,NA,NA,eel,14,NA,NA,NA,NA
cod,14,36,37.27,16697.7,A,herring,14,NA,NA,NA,NA,eel,14,NA,NA,NA,NA
cod,14,66,36.62,1203.7,C,herring,14,NA,NA,NA,NA,eel,14,NA,NA,NA,NA
cod,14,72,35.97,1465.9,B,herring,14,NA,NA,NA,NA,eel,14,NA,NA,NA,NA
")
我尝试过使用reshape函数,如下所示:
fish_df3 <- reshape(fish_df1, v.names = "var01", idvar = "st",
timevar = "species",
direction = "wide")
我认为我需要更多变量用于重塑函数的idvar部分。
我为没有更具体地提出这个问题而道歉,但我认为我的问题与我需要在函数中重新设置的参数有关,并且在标题中添加正确的参数名称我的问题可能会使我的问题更具体。 提前感谢您对此的任何帮助