如何在R中的循环中的临时数据框中找到值的索引

How to find index of value in a temporary dataframe in a loop in R

我想用 R 向数据框添加一列,它存储(作为字符向量)数据框中某些值的相对匹配位置与其在临时查找数据框中的相对行位置,我在循环中动态生成。

我提供了一些虚拟数据、一个我还没有设法开始工作的临时解决方案,以及一个明确的目标列,所有这些都是为了提供帮助。提前致谢。

请注意,我不受循环解决方案的约束,我尝试使用应用方法但运气不佳。

# the setup
band = data.frame(zep = c("page","plant","bonham","jones", "grant"), 
              age = c(36, 32, 32, 34, 45), 
              origin = c("heston", "westbrom", "redditch", "sidcup", "eastbourne"),
              alive = c(1,1,0,1,0), 
              rocked = c(1,1,1,1,0),
              active = c(59,  51, 18 ,55, 20), stringsAsFactors = F)

led_index 是一个数据框,我在其中存储了 'all' 我的 value/row 位置,并用于在每个唯一的 led_index$ 值上进行子集化,如 led_subbed

led_index = data.frame(value = c(rep("zep", 5), rep("origin", 5), rep("alive", 2), rep("rocked", 2)),
                   variable = c(band$zep, band$origin, 1,0,1,0),
                   stringsAsFactors = F)

并非我的所有 'band' 列都会进行此查找过程,但是,只有那些记录在向量 'subset_cols'

中的列
subset_cols = c("zep", "origin", "alive", "rocked")

我通过实例化一个新列来开始我的解决方案,我希望在该列中循环粘贴在 led_index(我命名为 led_subbed)的子集中找到的相对位置到

band$pass_string = character(nrow(band))

然后我使用 for 循环来填充这个新列,其中包含循环中四个临时 led_subbed 数据帧中的行位置(但是,我的解决方案似乎是从 led_index 而不是索引四个 led_subbed)。

for(i in 1:length(subset_cols)){

sub_name = subset_cols[i]

# subset led_index
led_subbed = led_index[led_index$value == sub_name,]
for(j in 1:length(led_subbed$value)){

band$pass_string = paste(band$pass_string, as.integer(row.names(led_subbed))[match(led_subbed$variable, band[,names(band) == sub_name])])
}}

我的目标列应如下所示,其中行位置取自应生成的四个 led_subbed 数据帧中的每一个,一个对应 subset_cols 中的每个值。

band$my_target_pass_string = c("1 1 1 1",  "2 2 1 1", "3 3 2 1",  "4 4 1 1",  "5 5 2 2")

我希望这一切都有意义吗?

这是一个使用 match

的想法
led_index$ind <- with(led_index, ave(variable, value, FUN = seq))  

do.call(paste, as.data.frame(sapply(band[subset_cols], function(i)
                                led_index$ind[match(i, led_index$variable)])))

#[1] "1 1 1 1" "2 2 1 1" "3 3 2 1" "4 4 1 1" "5 5 2 2"