x <- rnorm(10) ## random vector normal distributedx <- runif(10) ## random vector uniformly distributedx <- sample(1:100, 10) ## 10 random draws out of 1, 2, ..., 100x <- sample(LETTERS, 10) ## 10 random draws out of built-in latin alphabet
矩阵
m <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[1:4]))m# A B C D# A 1 4 7 10# B 2 5 8 11# C 3 6 9 12
数据帧
set.seed(42) ## for sake of reproducibilityn <- 6dat <- data.frame(id=1:n,date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),group=rep(LETTERS[1:2], n/2),age=sample(18:30, n, replace=TRUE),type=factor(paste("type", 1:n)),x=rnorm(n))dat# id date group age type x# 1 1 2020-12-26 A 27 type 1 0.0356312# 2 2 2020-12-27 B 19 type 2 1.3149588# 3 3 2020-12-28 A 20 type 3 0.9781675# 4 4 2020-12-29 B 26 type 4 0.8817912# 5 5 2020-12-30 A 26 type 5 0.4822047# 6 6 2020-12-31 B 28 type 6 0.9657529
#found based on the followingtypeof(mydf1), what it is.length(mydf1), how many elements it contains.attributes(mydf1), additional arbitrary metadata.
#If you cannot share your original data, you can str it and give an idea about the structure of your datahead(str(mydf1))
If I have a matrix x as follows:> x <- matrix(1:8, nrow=4, ncol=2,dimnames=list(c("A","B","C","D"), c("x","y")))> xx yA 1 5B 2 6C 3 7D 4 8>
How can I turn it into a dataframe with 8 rows, and threecolumns named `row`, `col`, and `value`, which have thedimension names as the values of `row` and `col`, like this:> x.dfrow col value1 A x 1...(To which the answer might be:> x.df <- reshape(data.frame(row=rownames(x), x), direction="long",+ varying=list(colnames(x)), times=colnames(x),+ v.names="value", timevar="col", idvar="row"))
我们不能直接复制粘贴它。
为了使问题和答案能够正确再现,请尝试在发布之前删除+和>,并将#用于输出和评论,如下所示:
#If I have a matrix x as follows:x <- matrix(1:8, nrow=4, ncol=2,dimnames=list(c("A","B","C","D"), c("x","y")))x# x y#A 1 5#B 2 6#C 3 7#D 4 8
# How can I turn it into a dataframe with 8 rows, and three# columns named `row`, `col`, and `value`, which have the# dimension names as the values of `row` and `col`, like this:
#x.df# row col value#1 A x 1#...#To which the answer might be:
x.df <- reshape(data.frame(row=rownames(x), x), direction="long",varying=list(colnames(x)), times=colnames(x),v.names="value", timevar="col", idvar="row")