英文:
Create a diagonal matrix from a dataframe in r
问题
我有这个数据框:
data.frame(Name = c("A", "B"),
Value = c(1,2))
我想得到一个矩阵,其中Name
值作为矩阵的行名和列名,值作为以下减法乘积的结果:
又被称为
英文:
I have this data frame:
data.frame(Name = c("A", "B"),
Value = c(1,2))
and I would like to arrive at a matrix with Name
values as the matrix's row names and column names and values as the product of a subtraction like the following
AKA
答案1
得分: 3
我假设您想要使用矩阵运算来完成,所以这是我的努力。
dd <- data.frame(Name = c("A", "B"),
Value = c(1,2))
M <- matrix( dd$Value, 2,2, dimnames=list( dd$Name, dd$Name))
M
# A B
#A 1 1
#B 2 2
M - t(M)
# A B
#A 0 -1
#B 1 0
如果您需要进一步的帮助,请告诉我。
英文:
I assumed you wanted it done with matrix operations, so here's my effort.
dd <- data.frame(Name = c("A", "B"),
Value = c(1,2))
M <- matrix( dd$Value, 2,2, dimnames=list( dd$Name, dd$Name))
M
# A B
#A 1 1
$B 2 2
M - t(M)
# A B
#A 0 -1
#B 1 0
答案2
得分: 2
你可以使用函数 outer
-
df <- data.frame(Name = c("A", "B"), Value = c(1,2))
mat <- t(outer(df$Value, df$Value, `-`))
dimnames(mat) <- list(df$Name, df$Name)
mat
# A B
#A 0 1
#B -1 0
英文:
You can use the function outer
-
df <- data.frame(Name = c("A", "B"), Value = c(1,2))
mat <- t(outer(df$Value, df$Value, `-`))
dimnames(mat) <- list(df$Name, df$Name)
mat
# A B
#A 0 1
#B -1 0
答案3
得分: 1
A tidyverse solution:
df <- data.frame(name = c("A", "B"), value = c(1,2))
df |>
bind_cols(df |> pivot_wider()) |>
transmute(across(A:B, \(x) x - value))
A B
1 0 1
2 -1 0
*注意,此示例中的 name
和 value
是小写。如果它们是大写的,或者存在其他列名,可以在 pivot_wider()
中使用 names_from
和 values_from
参数。
示例:pivot_wider(names_from = 'Name', values_from = "Value")
.
英文:
A tidyverse solution:
df <- data.frame(name = c("A", "B"), value = c(1,2))
df |>
bind_cols(df |> pivot_wider()) |>
transmute(across(A:B, \(x) x - value))
A B
1 0 1
2 -1 0
*Note name
and value
are lowercase in this example. If they are capitalized or if there are other column names, use the names_from
and values_from
args in pivot_wider()
.
Example: pivot_wider(names_from = 'Name', values_from = "Value")
.
答案4
得分: 1
使用 col()
进行索引的另一种方法:
mat <- array(df$Value, rep(nrow(df), 2), dimnames = list(df$Name, df$Name))
df$Value[col(mat)] - mat
# A B
# A 0 1
# B -1 0
请注意,我已经删除了代码部分并提供了翻译的内容。
英文:
An alternative approach with col()
for indexing:
mat <- array(df$Value, rep(nrow(df), 2), dimnames = list(df$Name, df$Name))
df$Value[col(mat)] - mat
# A B
# A 0 1
# B -1 0
答案5
得分: 1
这只是吗?
col(df) - df$value
[,1] [,2]
[1,] 0 1
[2,] -1 0
with(df, structure(col(df) - value, .Dimnames = list(name, name)))
A B
A 0 1
B -1 0
英文:
Isnt this just?
col(df) - df$value
[,1] [,2]
[1,] 0 1
[2,] -1 0
with(df, structure(col(df) - value, .Dimnames = list(name, name)))
A B
A 0 1
B -1 0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论