基于索引列创建一个新列 [英] Create a new column based on an index column
本文介绍了基于索引列创建一个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含n个观测值的数据集和一个包含观测索引的列,例如
I have a dataset containing n observation 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 like
col1 col2 col3 ID col_new
12 0 4 1 12
6 5 3 1 6
5 21 42 2 21
不带循环。其实我在
col_new <- rep(NA, length(ID))
for (i in 1:length(ID))
{
col_new[i] <- df[i, ID[i]]
}
是否有更好的方法( tidyverse
)?
Is there a better or (tidyverse
) way?
推荐答案
我们可以使用行/列
从基础R
进行索引
We can use row/column
indexing from 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
这篇关于基于索引列创建一个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文