【问题标题】:Using a column as a column index to extract value from a data frame in R使用列作为列索引从 R 中的数据框中提取值
【发布时间】:2019-11-14 03:54:27
【问题描述】:

我正在尝试使用列中的值来提取数据框中的列号。我的问题类似于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。

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

我应该在代码中修改什么,以便它将我的choice 列读取为列索引?

【问题讨论】:

  • 查看match(df$choice, colnames(df)) - 你的列没有命名为"1" "2" 等等,所以match 不起作用。
  • @thelatemail 你有建议的解决方法吗?
  • Ronak 已经把它盖住了。

标签: r indexing extraction


【解决方案1】:

由于您已经有了我们需要从数据框中提取的列号,因此我们在这里不需要match。但是,由于数据中有一个名为choice 的列,您在提取数据时不想考虑它,我们需要在从数据帧中设置子集之前将不在范围内的值转换为NA

mat <- cbind(seq_len(nrow(df)), df$choice)
mat[mat[, 2] > (ncol(df) -1), ] <- NA 
df$newValue <- 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

数据

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

【讨论】:

  • 您的代码取出作为输出的“newValue”列,并用我期望在“newValue”中的值替换“choice”...“choice”列应该是成为调用索引。
  • @mand3rd 是的,我弄乱了输出列名。我现在已经更正了,你能检查一下吗?
  • 它确实有效。你能澄清一下这行代码的含义吗:'mat[mat[, 2] > (ncol(df) -1), ]
  • @mand3rd 在choice 列中,您的值为 3,但您只想从df 中选择第一列和第二列的值,因为第三列是choice 列。所以在mat[mat[, 2] &gt; (ncol(df) -1), ] &lt;- NA 这一行中,我们将所有大于2的值替换为NA
猜你喜欢
  • 1970-01-01
  • 2021-04-09
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
相关资源
最近更新 更多