我新的R.我有數據幀操縱數據幀中的R
A 5 8 9 6
B 8 2 3 6
C 1 8 9 5
我要讓
A 5
A 8
A 9
A 6
B 8
B 2
B 3
B 6
C 1
C 8
C 9
C 5
我有一個大的數據文件
我新的R.我有數據幀操縱數據幀中的R
A 5 8 9 6
B 8 2 3 6
C 1 8 9 5
我要讓
A 5
A 8
A 9
A 6
B 8
B 2
B 3
B 6
C 1
C 8
C 9
C 5
我有一個大的數據文件
有人可以或許以更好的方式做到這一點,但在這裏我去... 我把你的數據放到一個叫做的數據框中
#repeat the value in the first column (c - 1) times were c is the number of columns (data[1,])
rep(data[,1], each=length(data[1,])-1)
#turning your data frame into a matrix allows you then turn it into a vector...
#transpose the matrix because the vector concatenates columns rather than rows
as.vector(t(as.matrix(data[,2:5])))
#combining these ideas you get...
data.frame(col1=rep(data[,1], each=length(data[1,])-1),
col2=as.vector(t(as.matrix(data[,2:5]))))
你可以簡化你的'col2'到'col2 = c(t(data [-1]))'。這樣你也不需要知道列的數量。 –
如果您可以使用矩陣,您可以將它「轉換」爲矢量並添加行名稱。我假定你真的想要'a','b','c'作爲行名。
n <- 3;
data <- matrix(1:9, ncol = n);
data <- t(t(as.vector(data)));
rownames(data) <- rep(letters[1:3], each = n);
如果你想保持rownames從第一個數據幀,這是ofcourse也可以在沒有庫。
n <- 3;
data <- matrix(1:9, ncol=n);
names <- rownames(data);
data <- t(t(as.vector(data)))
rownames(data) <- rep(names, each = n)
假設你開始是這樣的:
mydf <- structure(list(V1 = c("A", "B", "C"), V2 = c(5L, 8L, 1L),
V3 = c(8L, 2L, 8L), V4 = c(9L, 3L, 9L),
V5 = c(6L, 6L, 5L)),
.Names = c("V1", "V2", "V3", "V4", "V5"),
class = "data.frame", row.names = c(NA, -3L))
mydf
# V1 V2 V3 V4 V5
# 1 A 5 8 9 6
# 2 B 8 2 3 6
# 3 C 1 8 9 5
請嘗試以下之一:
library(reshape2)
melt(mydf, 1)
或者
cbind(mydf[1], stack(mydf[-1]))
或者
library(splitstackshape)
merged.stack(mydf, var.stubs = "V[2-5]", sep = "var.stubs")
雖然上例中的名稱模式不太可能適用於您的實際數據。
你需要重新檢查輸出,只有第三個解決方案是正確的:) –
@DavidArenburg,如果你指的是結果順序,我不是他們的猴子 - 頁面頂部有一個搜索表單字段,我肯定會指導他們如何重新排列'data.frame'的行。 :-) – A5C1D2H2I1M1N2O1R2T1
你已經嘗試過一些東西嗎? – Michiel
'library(reshape2);熔化(whatever_your_data_frame_is_called,id.vars =「name_of_your_first_column」)' – A5C1D2H2I1M1N2O1R2T1