سؤال

I am reading in parameter estimates from some results files that I would like to compare side by side in a table. But I cant get the dataframe to the structure that I want to have (Parameter name, Values(file1), Values(file2))

When I read in the files I get a wide dataframe with each parameter in a separate column that I would like to transform to "long" format using melt. But that gives only one column with values. Any idea on how to get several value columns without using a for loop?

paraA <- c(1,2)
paraB <- c(6,8)
paraC <- c(11,9)
Source <- c("File1","File2")
parameters <- data.frame(paraA,paraB,paraC,Source)

wrong_table <- melt(parameters, by="Source")
هل كانت مفيدة؟

المحلول

You can use melt in combination with cast to get what you want. This is in fact the intended pattern of use, which is why the functions have the names they do:

m<-melt(parameters)
dcast(m,variable~Source)
#   variable File1 File2
# 1    paraA     1     2
# 2    paraB     6     8
# 3    paraC    11     9

نصائح أخرى

Converting @alexis's comment to an answer, transpose (t()) pretty much does what you want:

setNames(data.frame(t(parameters[1:3])), parameters[, "Source"])
#       File1 File2
# paraA     1     2
# paraB     6     8
# paraC    11     9

I've used setNames above to conveniently rename the resulting data.frame in one step.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top