使用列作为列索引从R中的数据帧中提取值

问题描述 投票:1回答:1

我正在尝试使用列中的值来提取数据框中的列号。我的问题类似于r-bloggers中的主题。在此处复制脚本:

df <- data.frame(x = c(1, 2, 3, 4),
                 y = c(5, 6, 7, 8),
                 choice = c("x", "y", "x", "z"),
                 stringsAsFactors = FALSE)

但是,我没有在choice中使用列名,而是使用列索引号,这样我的数据框看起来像这样:

df <- data.frame(x = c(1, 2, 3, 4),
                 y = c(5, 6, 7, 8),
                 choice = c(1, 2, 1, 3),
                 stringsAsFactors = FALSE)

我尝试使用此解决方案:

df$newValue <-
  df[cbind(
    seq_len(nrow(df)),
    match(df$choice, colnames(df))
  )]

而不是给我这样的输出:

#   x y choice newValue
# 1 1 4   1        1
# 2 2 5   2        2
# 3 3 6   1        6
# 4 8 9   3        NA

我的newValue列返回所有NA。我应该在代码中进行哪些修改,以便它将choice列读取为列索引?

r indexing extraction
1个回答
1
投票

由于您具有需要从数据帧中提取的列号,因此此处不需要match。但是,由于在提取数据时您不希望考虑数据中的列choice,因此在从数据帧进行子集设置之前,我们需要将不在此范围内的值转换为NA

mat <- cbind(seq_len(nrow(df)), df$choice)
mat[mat[, 2] > (ncol(df) -1), ] <- NA 
df$choice <- df[mat]

df
#  x y choice newValue
#1 1 5      1        1
#2 2 6      2        6
#3 3 7      1        3
#4 4 8      3       NA
© www.soinside.com 2019 - 2024. All rights reserved.