根据代码填充R中的矩阵

发布于 2025-02-08 20:33:11 字数 398 浏览 2 评论 0原文

我有一个带有这样的代码的文件:

V1 V2 
1 1.0000000 
2 0.2000000 
3 0.5000000 
4 0.0000000 

一个带有以下代码的矩阵:

1 1 1 1 1 1 1 
3 3 3 3 3 3 3
4 2 4 2 4 2 4
1 1 1 1 1 1 1

我想使用循环制作一个新矩阵,其中每个值是代码的值,如下所示:

1.0 1.0 1.0 1.0 1.0 1.0 1.0
0.5 0.5 0.5 0.5 0.5 0.5 0.5
0.0 0.2 0.0 0.2 0.0 0.2 0.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0

有什么想法吗?

I have a file with codes like this:

V1 V2 
1 1.0000000 
2 0.2000000 
3 0.5000000 
4 0.0000000 

And one matrix with the codes like the following:

1 1 1 1 1 1 1 
3 3 3 3 3 3 3
4 2 4 2 4 2 4
1 1 1 1 1 1 1

I would like to use a loop to make a new matrix in which each value is the value of the codes as follows:

1.0 1.0 1.0 1.0 1.0 1.0 1.0
0.5 0.5 0.5 0.5 0.5 0.5 0.5
0.0 0.2 0.0 0.2 0.0 0.2 0.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薄情伤 2025-02-15 20:33:11

由于标签,您可以更轻松地做到这一点,但是通常您可以使用Match

数据:解决方案:

df_map <- data.frame(
  V1 = c(1, 2, 3, 4),
  V2 = c(1, 0.2, 0.5, 0)
)

m_codes <- matrix(sample(1:4, 32, TRUE), nrow = 4)

解决方案:

m_values <- matrix(df_map$V2[match(m_codes, df_map$V1)], nrow = nrow(m_codes))

Here you can do it somewhat easier because of labels, but in general you can use match:

data:

df_map <- data.frame(
  V1 = c(1, 2, 3, 4),
  V2 = c(1, 0.2, 0.5, 0)
)

m_codes <- matrix(sample(1:4, 32, TRUE), nrow = 4)

solution:

m_values <- matrix(df_map$V2[match(m_codes, df_map$V1)], nrow = nrow(m_codes))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文