One option is to row/column
index.
(一种选择是row/column
索引。)
Here, the row index can be sequence of rows, while the column index we get from match
ing the 'year' column of first data with the column names of second, cbind
the indexes to create a matrix
('m1') and use that to extract values from second dataset and assign those to 'value' column in first data (在这里,行索引可以是行序列,而我们通过将第一个数据的“ year”列与第二个列名进行match
而获得的列索引,将索引cbind
以创建matrix
(m1)并使用从第二个数据集中提取值,并将其分配给第一个数据中的“值”列)
i1 <- seq_len(nrow(df1))
j1 <- match(df1$year, names(df2)[-1])
m1 <- cbind(i1, j1)
df1$value <- df2[-1][m1]
df1
# letter year value
#1 A 2001 4
#2 B 2002 7
#3 C 2003 5
#4 D 2004 1
For the specific example, the pattern to extract seems to be the diag
onal elements, in that case, we can also use
(对于具体的例子,图案提取物似乎是diag
Onal地区的元素,在这种情况下,我们还可以使用)
df1$value <- diag(as.matrix(df2[-1]))
data (数据)
df1 <- structure(list(letter = c("A", "B", "C", "D"), year = 2001:2004),
class = "data.frame", row.names = c(NA,
-4L))
df2 <- structure(list(letter = c("A", "B", "C", "D"), `2001` = c(4L,
6L, 2L, 1L), `2002` = c(9L, 7L, 3L, 1L), `2003` = c(9L, 6L, 5L,
1L), `2004` = c(9L, 6L, 8L, 1L)), class = "data.frame",
row.names = c(NA,
-4L))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…