使用列作为列索引从 R 中的数据框中提取值
Using a column as a column index to extract value from a data frame in R
我正在尝试使用列中的值来提取数据框中的列号。我的问题类似于 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
列 returns 所有 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
。但是,由于数据中有一个名为 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))
我正在尝试使用列中的值来提取数据框中的列号。我的问题类似于 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
列 returns 所有 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
。但是,由于数据中有一个名为 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))