Yan*_*ann 4 r dataframe dplyr tidyverse
我有一个包含n个观察的数据集和一个包含观察指数的列,例如
col1 col2 col3 ID
12 0 4 1
6 5 3 1
5 21 42 2
Run Code Online (Sandbox Code Playgroud)
并希望根据我的索引创建一个新列
col1 col2 col3 ID col_new
12 0 4 1 12
6 5 3 1 6
5 21 42 2 21
Run Code Online (Sandbox Code Playgroud)
没有for循环.其实我在做
col_new <- rep(NA, length(ID))
for (i in 1:length(ID))
{
col_new[i] <- df[i, ID[i]]
}
Run Code Online (Sandbox Code Playgroud)
有更好的或(tidyverse
)方式吗?
对于一种可能的tidyverse
方法,如何使用dplyr::mutate
结合使用purrr::map2_int
.
library(dplyr)
library(purrr)
mutate(df, new_col = map2_int(row_number(), ID, ~ df[.x, .y]))
#> col1 col2 col3 ID new_col
#> 1 12 0 4 1 12
#> 2 6 5 3 1 6
#> 3 5 21 42 2 21
Run Code Online (Sandbox Code Playgroud)
数据
df <- read.table(text = "col1 col2 col3 ID
12 0 4 1
6 5 3 1
5 21 42 2", header = TRUE)
Run Code Online (Sandbox Code Playgroud)