我想创建一个类似于这样的tibble:
# A tibble: 3 x 4
team arsenal chelsea spurs
<chr> <chr> <chr> <chr>
1 arsenal self london north-london
2 chelsea london self london
3 spurs north-london london self 正如您所看到的,tibble中的信息是复制的。沿着第一排(阿森纳队),我们可以看到‘阿森纳’和‘马刺’之间的‘北伦敦’德比。同样地,沿着第三排(球队=马刺),在‘马刺’和‘阿森纳’之间还有‘北伦敦’德比。
让我们把这个叫做tibble。我用以下代码创建了它:
library(tidyverse)
## create vectors
team <- c("arsenal", "chelsea", "spurs")
arsenal <- c("self", "london", "north-london")
chelsea <- c("london", "self", "london")
spurs <- c("north-london", "london", "self")
## combine vectors into dataframe
df_derbies <- tibble(team, arsenal, chelsea, spurs)
df_derbies我的问题有两个:
( 1)是否有一种方法可以创建初始向量,使我不必键入重复信息?例如,这意味着我只需输入一次“北伦敦”。
( 2)在第一步之后,是否有一个函数可以像上面那样创建一个tibble?这将基本上重复行和列的相关组合的信息。
这样做的原因是,我想创建一个更大的tibble,最多有20行。我愿意接受更好的方法来创造和组合向量!
发布于 2019-06-11 16:18:09
您可以使用矩阵并使用基本R的upper.tri和lower.tri函数,如下所示:
## create vectors
team <- c("arsenal", "chelsea", "spurs")
arsenal <- c("self", "london", "north-london")
chelsea <- c("", "self", "london")
spurs <- c("", "", "self")
## combine vectors into dataframe
df_derbies <- rbind(arsenal, chelsea, spurs)
rownames(df_derbies) <- c("arsenal", "chelsea", "spurs")
colnames(df_derbies) <- c("arsenal", "chelsea", "spurs")
df_derbies[lower.tri(df_derbies)] <- df_derbies[upper.tri(df_derbies)]https://stackoverflow.com/questions/56547495
复制相似问题