Create a new column based on an index column

I have a dataset containing n observations and a column containing observation indices, e.g.

col1 col2 col3 ID
12    0    4    1
6     5    3    1
5     21   42   2

and want to create a new column based on my index, for example

col1 col2 col3 ID col_new
12    0    4    1   12
6     5    3    1   6
5     21   42   2   21

without loops. Actually i do

col_new <- rep(NA, length(ID))
for (i in 1:length(ID))
{
   col_new[i] <- df[i, ID[i]]
}

Is there a better way ( tidyverse)?

+4
source share
4 answers

We can use indexing row/columnfrom base R, which should be very fast.

df1$col_new <- df1[1:3][cbind(seq_len(nrow(df1)), df1$ID)]
df1$col_new
#[1] 12  6 21
+3
source

For a possible approach tidyverse, how about use dplyr::mutatein conjunction with 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

Data

df <- read.table(text = "col1 col2 col3 ID
12    0    4    1
6     5    3    1
5     21   42   2", header = TRUE)
+5
source

data.table:

library(data.table)
# Using OPs data
setDT(df)
df[, col_new := get(paste0("col", ID)), 1:nrow(df)]

# df
   col1 col2 col3 ID col_new
1:   12    0    4  1      12
2:    6    5    3  1       6
3:    5   21   42  2      21

:

  • : 1:nrow(df)
  • ID: get(paste0("col", ID))
  • Enter this value in a new column: col_new :=
+2
source

Another typing approach, this time using only tidyrand dplyr:

df %>%
    gather(column, col_new, -ID)  %>%  
    filter(paste0('col', ID) == column) %>%
    select(col_new) %>%
    cbind(df, .)

It's longer than @markdly's elegant one-liner, but if you're like me and embarrassed purrrmost of the time, it might seem easier.

+1
source

Source: https://habr.com/ru/post/1687994/


All Articles